ASP NET MVC 5 Delete File From Server

asp.net, asp.net-mvc, asp.net-mvc-5, c#, file-io

Solution

use `Request.MapPath`

string fullPath = Request.MapPath("~/Images/Cakes/" + photoName);
if (System.IO.File.Exists(fullPath))
{
   System.IO.File.Delete(fullPath);
}

Problem

View Code: ``` @if (File.Exists(Server.MapPath("~/Images/Cakes/" + Html.DisplayFor(modelItem => Model.CakeImage)))) { @model TastyCakes.Models.Cakes <form name="deletePhoto" action="/Cakes/DeletePhoto" method="post"> @Html.AntiForgeryToken() File name of image to delete (without .jpg extension): <input name="photoFileName" type="text" value="@Html.DisplayFor(modelItem => Model.CakeImage)" /> <input type="submit" value="Delete" class="tiny button"> </form> } else { <p>*File Needs to be uploaded</p> } ``` Controller Code: ``` [HttpPost] [ValidateAntiForgeryToken] public ActionResult DeletePhoto(string photoFileName) { ViewBag.deleteSuccess = "false"; var photoName = ""; photoName = photoFileName; var fullPath = Server.MapPath("~/Images/Cakes/" + photoName); if (File.Exists(fullPath)) { File.Delete(fullPath); ViewBag.deleteSuccess = "true"; } } ``` Where it says if (File.Exists) AND File.Delete, the code has squiggly lines underneath it. So I am trying to figure out what syntax I need to get thif file deleted. Here is a screenshot of my code in the controller: UPPDATE: I have got the code working and created a simple code example on my blog on how I got it working and how the idea came about. http://httpjunkie.com/2014/724/mvc-5-image-upload-delete/

Original source