我无法在 Application_Start 中获取当前的物理路径,使用:
HttpContext.Current.Request.PhysicalApplicationPath
因为那个时候没有 Request 对象。
还有什么其他方式可以获取物理路径?
protected void Application_Start(object sender, EventArgs e)
{
string path = Server.MapPath("/");
//or
string path2 = Server.MapPath("~");
//depends on your application needs
}
我使用ASP.Net WebForms创建了一个网站,您可以在Azure网站中使用的所有表单的结果中看到先前响应中提到的内容。
http://wfserverpaths.azurewebsites.net/
摘要:
Server.MapPath("/") => D:\home\site\wwwroot\
Server.MapPath("~") => D:\home\site\wwwroot\
HttpRuntime.AppDomainAppPath => D:\home\site\wwwroot\
HttpRuntime.AppDomainAppVirtualPath => /
AppDomain.CurrentDomain.BaseDirectory => D:\home\site\wwwroot\
HostingEnvironment.MapPath("/") => D:\home\site\wwwroot\
HostingEnvironment.MapPath("~") => D:\home\site\wwwroot\
var pathComponents = AppDomain.CurrentDomain.BaseDirectory.Split(':'); pathComponents[0] = @"\\" + System.Environment.MachineName; var resultPath = string.Join("", pathComponents);
- batressc你也可以使用
HttpRuntime.AppDomainAppVirtualPath
HttpRuntime.AppDomainAppPath
。该方法可以“获取当前应用程序域中托管的应用程序目录的物理驱动器路径”。而 HttpRuntime.AppDomainAppVirtualPath
则是获取虚拟路径,如 "/MyApp"。无论哪种情况,使用 HttpRuntime 是获取应用程序物理路径的最佳方式,因为它在每个上下文中都可用,包括在 HttpApplication
对象可用之前的静态上下文中。 - TriynkoServer
属性在应用程序事件(如“Application_Start”)或活动Web请求的上下文中访问HttpServerUtility
实例。 - TriynkoHttpRuntime.AppDomainAppPath
- Mehdi Khademloo使用 Server.MapPath("~")
方法。
HttpRuntime.AppDomainAppPath
比这些选项都要更好,因为它可以在任何上下文中使用,包括静态上下文,而所有其他选项都需要通过Server
属性访问HttpServerUtility
实例,该属性仅在应用程序事件(如“Application_Start”)或活动Web请求的上下文中可用。 - TriynkoAppDomain.CurrentDomain.BaseDirectory
AppDomain.CurrentDomain.BaseDirectory
因为它在系统命名空间中,且没有依赖于system.web
这样你的代码将会更加易于移植。
请使用以下代码
在asp.net中使用server.mappath()
在c# windows应用程序中使用application.startuppath
还有静态的HostingEnvironment.MapPath
System.AppDomain.CurrentDomain.BaseDirectory
这将给出您的应用程序的运行目录,即使是Web应用程序也适用。之后,您可以访问您的文件。
然而,所有这些选项之间存在一些细微差别
我发现
如果你这样做
string URL = Server.MapPath("~");
或者
string URL = Server.MapPath("/");
或者
string URL = HttpRuntime.AppDomainAppPath;
您的URL将像这样显示链接中的资源:
"file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"
但是如果您希望URL仅显示虚拟路径而不是资源位置,则应执行以下操作
string URL = HttpRuntime.AppDomainAppVirtualPath;
"http://HOME/Index/bin/Resources/HandlerDoc.htm"