IIS7.5部署站点后获取文件物理路径及web虚拟路径、以及获取通过Request.Uri获取部署地址信息

1、在部署到IIS后,我们保存文件需要获取实际物理地址及web虚拟地址,可以通过以下方式获取:

通过Hosting.HostingEnviroment获取物理地址和虚拟地址

var appPhysicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;//web程序部署物理地址,例如:D:\TFS\Energe
var appVirtualPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;//web程序虚拟根目录,例如:/GGFW
var localPath = appPhysicalPath + path;//服务器文件保存路径,path是相对路径
PathToList = appVirtualPath.TrimEnd('/') + path;//web虚拟路径,path是相对路径 

2、asp.net通过uri直接获取部署地址,利用GetLeftPart 方法获取。

GetLeftPart 方法返回一个包含 URI 字符串中最左边部分的字符串,它以 part 指定的部分结束。

在下面的情况下,GetLeftPart 包括分隔符:

  • Scheme 包括方案分隔符。

  • Authority 不包括路径分隔符。

  • Path 包括原始 URI 中的任何分隔符,一直到查询或段分隔符。

  • Query 包括 Path,并加上查询及其分隔符。

下面的示例演示一个 URI 以及使用 SchemeAuthorityPath 或 Query 调用 GetLeftPart 的结果。


利用该方法获取地址代码如下:

   public static string GetRootURI()
    {
        string AppPath = "";
        HttpContext HttpCurrent = HttpContext.Current;
        HttpRequest Req;
        if (HttpCurrent != null)
        {
            Req = HttpCurrent.Request;


            string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
            if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
                //直接安装在   Web   站点   
                AppPath = UrlAuthority;
            else
                //安装在虚拟子目录下   
                AppPath = UrlAuthority + Req.ApplicationPath;
        }
        return AppPath;
    }




猜你喜欢

转载自blog.csdn.net/yzy85/article/details/80543695