Working folder in ASP.NET

2019-01-28 00:59发布

问题:

We have a web application written in ASP.NET 3.5. In it, we access a file in the code-behind. (Ordinary C# file access, done on the server during the page life-cycle, this has nothing to do with URLs or web browsers).

On our production systems, we specify the full path to the file in question in the web.config. We'd like to be able to include a local copy of the file in the project in version control, and then to use a relative path in the version-controlled web.config to point to it, so that a checked-out copy of the application could be run from within Visual Studio's debugger without having to do any configuration.

The problem is that when the web application is running in debug mode, its working directory is neither the project nor the solution directory. In a windows or console application, in a project's properties page I can set the working directory. But in a web application I cannot.

Any ideas on how I can manage to make this work?

回答1:

To get the path of the root of the application:

//equivalent to Server.MapPath("/"); if at domain root, e.g Http://mysite.com/
string path = Server.MapPath("~");

This answer gives a rundown of a few different common Server.MapPath() uses that may also be of use to you.



回答2:

In code behind: HttpContext.Current.Server.MapPath("~")



回答3:

Use:

Server.MapPath("~");