为什么代字号和斜杠在Asp.net MVC应用程序中不起作用?

时间:2015-02-18 18:02:24

标签: c# asp.net asp.net-mvc

当我写这段代码时

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

这样的html代码编写时,它也能正常工作

2 个答案:

答案 0 :(得分:1)

HostingEnvironment.ApplicationPhysicalPathPath.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/"));