22

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/

1
  • OK, my filePath right now is \Images\Cakes\StrawberryCheesecake.jpg.jpg so I should be able to get this working.. Commented Mar 26, 2014 at 3:41

6 Answers 6

80

use Request.MapPath

string fullPath = Request.MapPath("~/Images/Cakes/" + photoName);
if (System.IO.File.Exists(fullPath))
{
   System.IO.File.Delete(fullPath);
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'll post a image of what the code looks like in the controller with these changes.
OK check out the image and you will see my error in the code. Do I need to use something other than File.Exists?
try with System.IO.File.Exists and System.IO.File.Delete
right now i am adding the extension manually like string finalpath = fullPath + ".jpg"; , but can we get file extension from server this way: string extension = Path.GetExtension(fullPath);
Like the simplicity!
7

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.

3 Comments

All squigglys have gone away, but It still is not deleting the photo.
@EricB Have you tried inspecting the generated HTML, to make sure the form is being created like you expected?
I added some session variables to help debug and figured out I was appending ".jpg" when I didnt need to giving me a path of "Whatever.jpg.jpg" I fixed it thanks for your help guys!
7

thanks for @Damith's Answer

I created this function

private bool RemoveFileFromServer(string path)
{
    var fullPath = Request.MapPath(path);
    if (!System.IO.File.Exists(fullPath)) return false;

    try //Maybe error could happen like Access denied or Presses Already User used
    {
        System.IO.File.Delete(fullPath);
        return true;
    }
    catch (Exception e)
    { 
        //Debug.WriteLine(e.Message);
    }
    return false;
}

and here is a simple use of it

RemoveFileFromServer("Content\img\ProfilePictures\User12.png");

Comments

2

you can also use HostingEnvironment.MapPath insted of Request.MapPath

This example works fine for me:

private bool DeleteFile(string image1_Address="")
        {
            try {
                if (image1_Address != null && image1_Address.Length > 0)
                {
                    string fullPath = HostingEnvironment.MapPath("~" + image1_Address);
                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                        return true;
                    }
                }
            }catch(Exception e)
            { }
            return false;
        }

Comments

1

Add using System.IO; at the top of your controller.

2 Comments

I have that. I thought the same thing, but I don't think that is part of System.IO Either way it's still showing squiggly lines in the same place.
Im gonna replace the image in a sec with one showing the error
0

Suppose you have a controller named PlacesController. make a IHostingEnvironment object in it and initialize it.

private readonly TouristPlaceInformationContext _context; //database context object. not necessary for this solving current problem. but it is used for database queries.
private readonly IHostingEnvironment _he;

public PlacesController(TouristPlaceInformationContext context, IHostingEnvironment he)
    {
        _context = context;
        _he = he;
    }

In the following function use _he.WebRootPath to get the path till "wwwroot" folder. use _he.ContentRootPath to get path till the root folder of the project. Suppose we want to delete a file in the following path: "projectRoot/wwwroot/images/somefile.jpg".Following function will get the job done.

public void deleteFile(string filename){
    String filepath= Path.Combine(_he.WebRootPath,"images", filename);
    if (System.IO.File.Exists(prevFilePath))
        {
             System.IO.File.Delete(prevFilePath);

        }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.