检查asp.net mvc 5中是否存在文件

我正在检查是否存在无法找到它的文件,无论它是否存在

if (System.IO.File.Exists("~/files/downloads/" + fileCode + ".pdf")) { return File("~/files/downloads/" + fileCode, "application/pdf", Server.UrlEncode(fileCode)); } else { return View("ErrorNotExistsView"); } 

如何修改代码以正确检查文件是否存在?

如果提供绝对路径或相对路径, System.IO.File将起作用。 相对路径不是相对于HTML根文件夹,而是相对于当前工作目录 。 当前工作目录将是一个类似C:\Program Files (x86)\IIS Express

文件路径开头的~字符仅被解释为当前ASP.NET上下文的一部分, File方法对此一无所知。

如果您使用的是控制器方法,则可以使用对象HttpContext.Server ,否则(例如在View中)可以使用HttpContext.Current.Server.MapPath

  var relativePath = "~/files/downloads/" + fileCode + ".pdf"; var absolutePath = HttpContext.Server.MapPath(relativePath); if(System.IO.File.Exists(absolutePath)) .... 

如果应用程序没有足够的权限来访问该文件,Exists()可以返回false。 因此,您应该将这些文件授予appPool特定的文件夹和文件。

这是我的解决方案:

  @{ var profileImg = "/Images/" + User.Identity.GetUserId() + ".jpg"; var absolutePath = HttpContext.Current.Server.MapPath(profileImg); if (System.IO.File.Exists(absolutePath)) { image } else { image } }  

File.Exists()将需要完整路径。 尝试使用类似的东西:

@"C:\users\yourUsername\myDocuments\files\\downloads\" + fileCode + ".pdf"

代替:

"~/files/downloads/" + fileCode + ".pdf"