I have had a real nightmare with Server.MapPath()
. When I call Server.MapPath("~")
in my application that is running in ASP.NET Development Server it returns root directory that ends in a back slash like f:\projects\app1\
, but I call it in published version, installed in IIS, it returns root directory without any back slash like c:\inetpub\wwwroot\app1
. Why this happens? How could avoid?
I did 2 scenarios on a same machine: Windows Server 2008 R2 x64, Visual Studio 2010 x64, IIS 7.
UPDATE:
Why I care about it? Ineed I have wrote a custom site map provider based on file/folder structure. It extracts list of file/folders of root directory "~"
, replaces root directory section with Server.MapPath("~")
in order to generate URL of .aspx
files for use in ASP.NET Menu
control. I think following code explains what I'm doing:
string mainRoot = HttpContext.Current.Server.MapPath("~");
DirectoryInfo di = new DirectoryInfo(mainRoot);
//added to solve this problem with Server.MapPath
if (!mainRoot.EndsWith(@"\"))
mainRoot += @"\";
FileInfo[] files = di.GetFiles("*.aspx");
foreach (FileInfo item in files)
{
string path = item.FullName.Replace(mainRoot, "~/").Replace(@"\", "/");
//do more here
}
It could be from when you set up the virtual directory inside of IIS, depending on whether you used a trailing slash when setting it up.
But does it really matter? Why would you even care what Server.MapPath("~")
returns? I can't imagine you'd ever use it just like that. Much more likely is when you actually need a path to something inside your application:
Server.MapPath("~/Something/Foo.txt");
In addition, whenever you build up paths, you should try to get into the habit of using Path.Combine, because you don't need to worry about trailing slashes at all then:
string fullPath = Path.Combine(Server.MapPath("~"), @"Something\Foo.txt");