How to get the physical path of a virtual directory

As we know, the virtual manager can be associated with a folder with a different name, how can I get the physical path to the virtual directory?

I tried with HttpContext.Current.server.MapPath, but it returns me the physical path plus the path that I send to the parameter, even if the directory does not exist at all or exists with a different name.

Example:

C: \ blabla \ sites \ Application1 \ Imaageesss - On disk

Application1 \ Images (In ISS, my virutal directory)

But if I do MapPath on "/ Images", it will never give me C: \ blabla \ Sites \ Application1 \ Imaageesss, but C: \ inetpub \ wwwroot \ Images that are not a real directory related to.

+8
source share
5 answers
Server.MapPath("~/Images") 

- this is the right way because "~" refers to the root of your application.

+9
source share

This is what worked for me:

 string physicalPath = System.Web.Hosting.HostingEnvironment.MapPath(HttpContext.Current.Request.ApplicationPath); 
+5
source share

What if you try this small piece?

 string physicalPath = HttpContext.Current.Request.MapPath(appPath); 
+2
source share

After some more research, I managed to create a method to get the physical path to the IIS virtual directory:

 public static string VirtualToPhysicalPath(string vPath) { // Remove query string: vPath = Regex.Replace(vPath, @"\?.+", "").ToLower(); // Check if file is in standard folder: var pPath = System.Web.Hosting.HostingEnvironment.MapPath("~" + vPath); if (System.IO.File.Exists(pPath)) return pPath; // Else check for IIS virtual directory: var siteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName(); var sm = new Microsoft.Web.Administration.ServerManager(); var vDirs = sm.Sites[siteName].Applications[0].VirtualDirectories; foreach (var vd in vDirs) { if (vd.Path != "/" && vPath.Contains(vd.Path.ToLower())) pPath = vPath.Replace(vd.Path.ToLower(), vd.PhysicalPath).Replace("/", "\\"); } return pPath; } 

Caution: this solution assumes that you have only the root application (Applications [0]).

+1
source share

This may answer your question:

http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx

However, at present I cannot give an example, because I have a lot of work. When I find some time, I will send detailed information.

0
source share

All Articles