Getting current directory in .NET web application

后端 未结 2 773
终归单人心
终归单人心 2020-11-28 22:12

So I have a web project, and I\'m trying to get the root directory of the website using the c# method Directory.GetCurrentDirectory(). I don\'t want to be usin

相关标签:
2条回答
  • 2020-11-28 22:28

    Use this code:

     HttpContext.Current.Server.MapPath("~")
    

    Detailed Reference:

    Server.MapPath specifies the relative or virtual path to map to a physical directory.

    • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
    • Server.MapPath("..") returns the parent directory
    • Server.MapPath("~") returns the physical path to the root of the application
    • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

    An example:

    Let's say you pointed a web site application (http://www.example.com/) to

    C:\Inetpub\wwwroot
    

    and installed your shop application (sub web as virtual directory in IIS, marked as application) in

    D:\WebApps\shop
    

    For example, if you call Server.MapPath in following request:

    http://www.example.com/shop/products/GetProduct.aspx?id=2342
    

    then:

    Server.MapPath(".") returns D:\WebApps\shop\products
    Server.MapPath("..") returns D:\WebApps\shop
    Server.MapPath("~") returns D:\WebApps\shop
    Server.MapPath("/") returns C:\Inetpub\wwwroot
    Server.MapPath("/shop") returns D:\WebApps\shop
    

    If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

    If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

    Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

    Footnotes

    Server.MapPath(null) and Server.MapPath("") will produce this effect too.

    0 讨论(0)
  • 2020-11-28 22:39

    The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

    You want HttpRuntime.AppDomainAppPath.

    If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

    0 讨论(0)
提交回复
热议问题