Подтвердить что ты не робот

ASP.NET MVC 5 Удалить файл с сервера

Просмотр кода:

@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>
}

Код контроллера:

[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";
        }
}

Где он говорит, что (File.Exists) AND File.Delete, код имеет под ним строчки. Поэтому я пытаюсь выяснить, какой синтаксис мне нужен, чтобы удалить файл thif.

Вот скриншот моего кода в контроллере: enter image description here

UPPDATE: У меня есть код, который работает и создал простой пример кода в моем блоге о том, как я получил его работу и как появилась идея. http://httpjunkie.com/2014/724/mvc-5-image-upload-delete/

4b9b3361

Ответ 1

использовать Request.MapPath

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

Ответ 2

File, поскольку вы используете его, является неоднозначным, следовательно, "squiggly line". IDE не может решить, что вы имеете в виду;

System.Web.Mvc.Controller.File()

или

System.IO.File

Используйте полное имя при попытке использовать API файлов в контроллере MVC.

Ответ 3

спасибо за @Damith Answer

Я создал эту функцию

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;
}

и здесь это простое использование

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

Ответ 4

Добавьте using System.IO; в верхнюю часть вашего контроллера.

Ответ 5

вы также можете использовать HostingEnvironment.MapPath insted из Request.MapPath

Этот пример отлично подходит для меня:

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;
        }

Ответ 6

Предположим, у вас есть контроллер с именем PlacesController. создайте в нем объект IHostingEnvironment и инициализируйте его.

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;
    }

В следующей функции используйте _he.WebRootPath, чтобы получить путь до папки "wwwroot". используйте _he.ContentRootPath, чтобы получить путь до корневой папки проекта. Предположим, мы хотим удалить файл по следующему пути: "projectRoot/wwwroot/images/somefile.jpg". Следующая функция выполнит работу.

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

        }
}