Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET MVC 5 Delete File From Server

Tags:

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: 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. http://httpjunkie.com/2014/724/mvc-5-image-upload-delete/

like image 346
Eric Bishard Avatar asked Mar 26 '14 03:03

Eric Bishard


People also ask

How do you force delete a file in C#?

There is only one method that you need to call, namely WipeFile and the code is as shown below. So, all you really have to do is call WipeFile and supply the full path of the file to be deleted, as well as the number of times you want to overwrite it.


2 Answers

use Request.MapPath

string fullPath = Request.MapPath("~/Images/Cakes/" + photoName); if (System.IO.File.Exists(fullPath)) {    System.IO.File.Delete(fullPath); } 
like image 198
Damith Avatar answered Oct 24 '22 18:10

Damith


File, as you're using it, is ambiguous, hence the "squiggly line". The IDE can't resolve which you mean;

System.Web.Mvc.Controller.File()

or

System.IO.File

Use a fully-qualified name when trying to use the File API within an MVC controller.

like image 27
Tieson T. Avatar answered Oct 24 '22 18:10

Tieson T.