Check file availability in asp.net mvc 5

I check the presence of the bu file, I can not find it, regardless of whether it is or not.

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

How can I change the code to check for the presence of a file correctly?

+10
source share
4 answers

System.IO.File will work if you specify an absolute or relative path. The relative path will be relative not to the HTML root folder, but to the current working directory. The current working directory will be of type C:\Program Files (x86)\IIS Express .

The ~ character at the beginning of the file path is interpreted only as part of the current ASP.NET context, of which the File methods do not know anything.

If you are in the controller method, you can use the HttpContext.Server object, otherwise (for example, in the view) you can use HttpContext.Current.Server .

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

Exists () may return false if the application does not have sufficient file permissions. Therefore, you must provide their appPool in specific folders and files.

+2
source

Here is my solution:

 <span> @{ var profileImg = "/Images/" + User.Identity.GetUserId() + ".jpg"; var absolutePath = HttpContext.Current.Server.MapPath(profileImg); if (System.IO.File.Exists(absolutePath)) { <img alt="image" width="50" height="50" class="img-circle" src="@profileImg" /> } else { <img alt="image" width="50" height="50" class="img-circle" src="~/Images/profile_small.jpg" /> } } </span> 
+2
source

File.Exists () will need the full path. Try using something like:

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

instead:

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

0
source

All Articles