+977-9849845061

Using File.Exists() to check if file exist in MVC 5

I had an case to show default No-Image Found Image on my customer site if there is no any Image attached with the Product. It is a good practice to show a default Image when there is no image of the post on the site.

File.Exists() determines whether the specified file exists.

  • Returns true if the caller has the required permissions and path contains the name of an existing file; Returns
  • Returns false if the caller has the required permissions and path contains the name of an existing file.
  • Also returns false if a path is a null, an invalid path, or a zero-length string.
  • If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of a path.

Reference: File.Exists Method(String)

 

Case I: Show Default Image when Image Location is not provided or null. 

Implementation Level: View Level

System.IO.File.Exists() determines whether the specified file exists.

Server.MapPath() maps the specified relative or virtual path to the corresponding physical directory on the server.


Case II: When the user has to delete associated files when deleting a Post from Database. 

Implementation Level: Controller Level

 

System.IO.File.Delete(fullPath) will delete the file from the server.

Request.MapPath returns the physical file path that corresponds to the specified virtual path.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...