当我写这段代码时
string[] filePaths = Directory.GetFiles(@"~/Content/Images/");
我得到System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\IIS Express\Content\Images'
。
我该怎么写得正确?我有文件夹“Images”和“Content”,我不想硬编码路径。此外,当我使用像<img src="~/Content/Images/Img.jpg" for example
答案 0 :(得分:1)
将HostingEnvironment.ApplicationPhysicalPath
与Path.Combine
一起使用,例如:
string[] filePaths = Directory.GetFiles(Path.Combine
(HostingEnvironment.ApplicationPhysicalPath,
"Content/Images"));
或者
使用HttpContext.Current.Server.MapPath
,例如:
string[] filePaths = Directory.GetFiles(HttpContext.Current.Server.MapPath
(@"~/Content/Images/"));
答案 1 :(得分:0)
MVC有自己的HttpContext(HttpContextBase),它来自Controller。如果要使用常规上下文,只需使用完全限定名称
string[] filePaths = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath
(@"~/Content/Images/"));