简体   繁体   English

在mvc应用上使用相对路径定位文件

[英]targeting file using relative path on mvc app

I want to access to the file on my web project under content folder, and I want to use relative path. 我想访问Web项目中内容文件夹下的文件,并且我想使用相对路径。 Can someone confirm me that I'm using right approach 有人可以确认我在使用正确的方法吗

string file = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/myfile.txt");   

yes its 100% right. 是的,它100%正确。 When you execute the code outside the context of a http request then HttpContext.Current is null and your code crashes. 当您在http请求的上下文之外执行代码时,HttpContext.Current为null,并且代码崩溃。 HostingEnvironment.MapPath always works HostingEnvironment.MapPath始终有效

In this scenario i have used this approach to get multiple files and it worked fine ,so i recommend this . 在这种情况下,我使用了这种方法来获取多个文件,并且效果很好,所以我建议这样做。 try it once 尝试一次

 String[] files = Directory.GetFiles(@HostingEnvironment.ApplicationPhysicalPath + "\\Videos\\");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM