When I write this code
string[] filePaths = Directory.GetFiles(@"~/Content/Images/");
I get System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\\Program Files (x86)\\IIS Express\\Content\\Images'
. How should I write correctly? I have the folder "Images" and "Content", and I dont want to hardcode a path. Also, it works when I write in html code like <img src="~/Content/Images/Img.jpg" for example
Use HostingEnvironment.ApplicationPhysicalPath
with Path.Combine
, like:
string[] filePaths = Directory.GetFiles(Path.Combine
(HostingEnvironment.ApplicationPhysicalPath,
"Content/Images"));
Or
Use HttpContext.Current.Server.MapPath
, like:
string[] filePaths = Directory.GetFiles(HttpContext.Current.Server.MapPath
(@"~/Content/Images/"));
MVC has its own HttpContext (HttpContextBase) which it gets from Controller. If you want to use the general context you just need to use the fully qualified name
string[] filePaths = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath
(@"~/Content/Images/"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.