简体   繁体   中英

Path Problem in ASP.net

I am trying to do the following I am building asp.net website with c# language I want to read 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"
);

使用HttpContext.Current可以访问HTTP请求的Request,Server,Response和其他对象。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM