开发者

Path Problem in ASP.net

I am trying to do the following I am building asp.net website with c# language I want to re开发者_如何学Pythonad a text file from my project(the file is inside the project) I tried to get the file Path by this way :

string path=Request.PhysicalApplicationPath+"filename.txt";

but I can't use The "Request" object from separated C# file ?? note: separated C3 file,I mean it's not related with aspx file can you help me with my way or do you have another way ?? thx


I would recommend you passing the path to your library from the web application. So for example in your web app:

var path = Server.MapPath("~/filename.txt");
var result = BusinessLayer.SomeMethod(path);

You could also use HostingEnvironment in your class library but I would really advice you against it as it creates a dependency with System.Web which makes your class library tied to a web context and not unit testable friendly:

var path = Path.Combine(
    HostingEnvironment.ApplicationPhysicalPath, 
    "filename.txt"
);


Using HttpContext.Current you have access to Request, Server, Response and other objects of the HTTP request.


but I can't use The "Request" object from separated C# file ??

I'm guessing you mean this is in a dll? If so, then you can get to it by referencing system.web in the separate dll, and getting at the httpcontext.current object


I would use some sort of injection mechanism either to give the application root path to the class or a copy of the current context/request to the class that it can use. Essentially, you want to give the class the means to find the path (or even give it the path) rather than use a fixed dependency that is hard to recreate in testing. To simplify my example, I'll use the Request as you are doing, though, you could easily provide just the base path of the application as a string as well.

public class Foo
{
     // HttpRequestBase may be more appropriate
     private HttpRequest Request { get; set; }

     public Foo( HttpRequest request )
     {
         this.Request = request;
     }

     public void Bar()
     {
          string path = Path.Combine( this.Request.PhysicalApplicationPath,
                                      "filename.txt" );
          ...
     }
}

Note that you could combine this with @Darin's ideas on how to calculate the server path as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜