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 包括分隔符:
下面的示例演示一个 URI 以及使用 Scheme、Authority、Path 或 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;
}