所以我有一个Web项目,我正在尝试使用c#方法Directory.GetCurrentDirectory()
获取网站的根目录。我不想使用静态路径,因为文件位置将来会发生变化。这个方法在我的imageProcess.aspx.cs文件中运行,但我认为它会返回:
C:\Users\tcbl\documents\visual studio 2010\Projects\ModelMonitoring\ModelMonitoring\imageProcess.aspx.cs
我反而得到了:
C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\
任何人都可以解释为什么会发生这种情况以及可能的解决方案是什么?非常感谢。
答案 0 :(得分:193)
当前目录是系统级功能;它返回启动服务器的目录。它与网站无关。
您想要HttpRuntime.AppDomainAppPath
。
如果您在HTTP请求中,也可以拨打Server.MapPath("~/Whatever")
。
答案 1 :(得分:95)
使用此代码:
HttpContext.Current.Server.MapPath("~")
详细参考:
Server.MapPath
指定映射到物理目录的相对或虚拟路径。
Server.MapPath(".")
返回当前的物理目录
正在执行的文件(例如aspx)Server.MapPath("..")
返回父目录Server.MapPath("~")
返回到根目录的物理路径
应用Server.MapPath("/")
返回到根目录的物理路径
域名(不一定与域名的根目录相同)
应用程序)一个例子:
假设您将网站应用程序(http://www.example.com/)指向
C:\Inetpub\wwwroot
并在
中安装了您的商店应用程序(子网站为IIS中的虚拟目录,标记为应用程序)D:\WebApps\shop
例如,如果您在以下请求中致电Server.MapPath
:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
然后:
Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
如果Path以正向(/)或反斜杠()开头,则MapPath
方法返回一条路径,就像Path是一条完整的虚拟路径一样。
如果Path不以斜杠开头,则MapPath
方法返回相对于正在处理的请求的目录的路径。
注意:在C#中,@是逐字文字字符串运算符,意味着该字符串应“按原样”使用,不能为转义序列处理。
脚注
Server.MapPath(null)
和Server.MapPath("")
也会产生这种效果。