Bud*_*Joe 277 .net asp.net-mvc absolute-path
从ASP.NET MVC项目中的Controller查找App_Data文件夹的绝对路径的正确方法是什么?我希望能够临时使用.xml文件,我不想硬编码路径.
这不起作用:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");
//.... do whatever
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
我认为在Web上下文之外VirtualPathUtility.ToAbsolute()不起作用.字符串路径返回"C:\ App_Data\somedata.xml"
我应该在哪里确定MVC应用程序中.xml文件的路径?global.asax并坚持使用应用程序级变量?
eu-*_*-ne 391
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
Run Code Online (Sandbox Code Playgroud)
string path = Server.MapPath("~/App_Data/somedata.xml");
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 270
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
Run Code Online (Sandbox Code Playgroud)
这是获得它的最"正确"方式.
Sim*_*ver 134
我试图养成使用的习惯,HostingEnvironment而不是Server在WCF服务的上下文中使用它.
HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");
Run Code Online (Sandbox Code Playgroud)
最正确的方法是使用HttpContext.Current.Server.MapPath("~/App_Data");.这意味着您只能从HttpContext可用的方法中检索路径.这是有道理的:App_Data目录是一个Web项目文件夹结构[1].
如果您需要从无法访问的类中获取〜/ App_Data的路径,则HttpContext可以始终使用IoC容器注入提供程序接口:
public interface IAppDataPathProvider
{
string GetAppDataPath();
}
Run Code Online (Sandbox Code Playgroud)
使用您的实现它HttpApplication:
public class AppDataPathProvider : IAppDataPathProvider
{
public string GetAppDataPath()
{
return MyHttpApplication.GetAppDataPath();
}
}
Run Code Online (Sandbox Code Playgroud)
其中MyHttpApplication.GetAppDataPath的样子:
public class MyHttpApplication : HttpApplication
{
// of course you can fetch&store the value at Application_Start
public static string GetAppDataPath()
{
return HttpContext.Current.Server.MapPath("~/App_Data");
}
}
Run Code Online (Sandbox Code Playgroud)
[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx
Phil Haak有一个例子,我认为在使用疯狂的"\"样式目录分隔符处理路径时会更稳定一些.它还安全地处理路径连接.它在System.IO中免费提供
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
Run Code Online (Sandbox Code Playgroud)
但是,您也可以尝试"AppDomain.CurrentDomain.BaseDirector"而不是"Server.MapPath".
string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");
Run Code Online (Sandbox Code Playgroud)
或者
string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246014 次 |
| 最近记录: |