How to get virtual directory physical path

前端 未结 6 2186
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 20:55

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 Ht

相关标签:
6条回答
  • 2021-01-04 21:33

    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.

    0 讨论(0)
  • 2021-01-04 21:34

    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]).

    0 讨论(0)
  • 2021-01-04 21:44

    The following should work just fine:

    var physicalPath = HostingEnvironment.MapPath("~/MyVirtualDirectory");
    
    0 讨论(0)
  • 2021-01-04 21:45

    This is what worked for me:

    string physicalPath =    
    System.Web.Hosting.HostingEnvironment.MapPath(HttpContext.Current.Request.ApplicationPath);
    
    0 讨论(0)
  • 2021-01-04 21:46

    What if you try this little snippet?

    string physicalPath = HttpContext.Current.Request.MapPath(appPath);
    
    0 讨论(0)
  • 2021-01-04 21:54
    Server.MapPath("~/Images")
    

    is the correct way to go about it as "~" references the root of your application.

    0 讨论(0)
提交回复
热议问题