Eric B Eric B - 1 year ago 207
ASP.NET (C#) Question

ASP NET MVC 5 Delete File From Server

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">
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">
} else {
<p>*File Needs to be uploaded</p>

Controller Code:

public ActionResult DeletePhoto(string photoFileName)

ViewBag.deleteSuccess = "false";
var photoName = "";
photoName = photoFileName;
var fullPath = Server.MapPath("~/Images/Cakes/" + photoName);

if (File.Exists(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:
enter image description here

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.

Answer Source

use Request.MapPath

string fullPath = Request.MapPath("~/Images/Cakes/" + photoName);
if (System.IO.File.Exists(fullPath))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download