Reputation: 2842
As we know that a virtual direcoty can be linked to a folder with a diffrent name, how can I get the physical path of a virtual directory ?
I've been trying with HttpContext.Current.server.MapPath but it returns me the physic path plus the path I send in parameter even if the directory doesn't even exist or if it exists with a diffrent name.
Exemple :
C:\blabla\Sites\Application1\Imaageesss - On disc
Application1\Images (In ISS, my virutal directory)
But if I do a MapPath on "/Images" it will never give me C:\blabla\Sites\Application1\Imaageesss but C:\inetpub\wwwroot\Images which is not the real directory linked to.
Upvotes: 16
Views: 41380
Reputation: 91
The following should work just fine:
var physicalPath = HostingEnvironment.MapPath("~/MyVirtualDirectory");
Upvotes: 1
Reputation: 1096
After some more research I was able to create a method to get the physical path of a virtual IIS 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;
}
Caveat: this solution assumes that you only have a root application (Applications[0]).
Upvotes: 1
Reputation: 596
Server.MapPath("~/Images")
is the correct way to go about it as "~" references the root of your application.
Upvotes: 16
Reputation: 5660
This is what worked for me:
string physicalPath =
System.Web.Hosting.HostingEnvironment.MapPath(HttpContext.Current.Request.ApplicationPath);
Upvotes: 9
Reputation: 81
This might answer your question:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx
However, I can't currently provide an example, because I have got a lot of work to do. When I'll find some time I'll send detailed information.
Upvotes: 0
Reputation: 2106
What if you try this little snippet?
string physicalPath = HttpContext.Current.Request.MapPath(appPath);
Upvotes: 3