Hi all,
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
}