How to get virtual directory physical path

前端 未结 6 2185
没有蜡笔的小新
没有蜡笔的小新 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: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]).

提交回复
热议问题