Asp.net core 可以添加图片,但是无法删除图片

Asp.net core I could add pictures, but I couldn't delete the image

我正在使用 Asp.Net MVC 核心。我可以添加图片,但无法删除图像。我无法使用以下方法:Server、MapPath。

实体添加和图片上传:(成功method.I刚刚和大家分享了我是如何添加的。)

  public async Task<IActionResult> Create(IFormFile image,Programci programci)
    {
        if (image==null || image.Length==0)
        {
            return Content("not image selected");
        }

        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/image/Programcilar", image.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await image.CopyToAsync(stream);

        }

        programci.ImageUrl = "/image/Programcilar/"+ image.FileName;
        _programciService.Add(programci);

        return RedirectToAction("Index");
    }

删除方法:(Problem.I无法删除图片。)

 public ActionResult Delete(int id)
    {
        var bulunanProgramci = _programciService.Get(id);


        _programciService.Delete(id);
        return RedirectToAction("Index");
    }

根据您的代码和图像,您应该在 _programciService.Delete(id); 方法调用

中的代码中包含类似这样的内容
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\image\Programcilar", "controlller.jpg");

if(System.IO.File.Exists(path))
{
    System.IO.File.Delete(path);
}

只需将静态图像文件名 "controlller.jpg" 替换为您要删除的图像的变量名即可。

注意图片的路径。它应该是根驱动器的完整路径。例如 C:\inetpub\wwwroot\image\Programcilar\controlller.jpg

我建议使用环境变量来 store/retrieve 您存储图像的路径。

string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Images");
        var path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), uploadsFolder, picName);

        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }

别忘了使用:

private readonly IWebHostEnvironment webHostEnvironment;

并在 class 的构造函数中实例化它:

public yourClass(yourContext context, IWebHostEnvironment hostEnvironment)
    {
        _context = context;
        webHostEnvironment = hostEnvironment;
    }