Getting the current directory in a .NET web application

So, I have a web project, and I'm trying to get the root directory of a website using the C # Directory.GetCurrentDirectory() method. I do not want to use a static path, as the location of the files will change in the future. This method works in my imageProcess.aspx.cs file, but where I thought it would return:

 C:\Users\tcbl\documents\visual studio 2010\Projects\ModelMonitoring\ModelMonitoring\imageProcess.aspx.cs 

I get:

 C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\ 

Can someone explain why this is happening and what is the possible solution? Thank you very much.

+74
c # directory filepath
Jun 08 2018-12-12T00:
source share
2 answers

The current directory is a system level; it returns the directory from which the server was started. This has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath .

If you are using an HTTP request, you can also call Server.MapPath("~/Whatever") .

+142
Jun 08 2018-12-12T00:
source share

Use this code:

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

Detailed description:

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

  • Server.MapPath(".") Returns the current physical directory of the file (for example, aspx)
  • 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 (not necessarily the same as the application root)

Example:

Say you pointed the website app ( http://www.example.com/ ) to

 C:\Inetpub\wwwroot 

and installed your storeโ€™s application (sub-web as virtual directory in IIS, marked as application) in

 D:\WebApps\shop 

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

 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 the Path begins with a forward (/) or backslash (), the MapPath method returns the path as if the Path was a full, virtual path.

If the path does not start with a slash, the MapPath method returns the path relative to the directory of the request being processed.

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

Footnote

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

+67
Dec 16 '14 at 8:51
source share



All Articles