我试图获取我的网站根目录中的文件夹的路径,并在调用我的控制器构造函数时将其保存到类属性:
public TestController:Controller{
string temp;
public TestController(){
temp = "";
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
temp = Server.MapPath("~/TheFolder/"); // Server is null - error.
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error.
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
lia*_*nan 28
AppDomain.CurrentDomain.BaseDirectory将为您提供站点的根目录.所以:
temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder");
Run Code Online (Sandbox Code Playgroud)
(感谢Marc Gravell的评论)
在构造函数中你真的需要这个路径吗?如果您在主页循环开始之前不需要它,请考虑推迟它 - 只需使用常规属性; 就像是
public string BasePath {
get { return Server.MapPath("~/TheFolder/"); }
}
Run Code Online (Sandbox Code Playgroud)
然后,当在页面循环期间使用它时,它应该没问题.如果你真的想要,你可以缓存它,但我不认为这将成为一个瓶颈:
private string basePath;
public string BasePath {
get {
if(basePath == null) basePath = Server.MapPath("~/TheFolder/");
return basePath;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7653 次 |
| 最近记录: |