Problem deleting image

2

I have an image that is the avatar of my user, hence I need to delete and I have the following code snippets:

Action that is used in importing the file

public void MinhaActionParaImport()
{
    var arquivo = Request.Files[0];
    var caminho = Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg");
    arquivo.SaveAs(caminho);
}

Method used to remove image

public void DeletarImagem()
{
    var imagem = Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg");
    if (System.IO.File.Exists(imagem))
        System.IO.File.Delete(imagem);
}

Method used to display the image

public ActionResult ExibirImagem()
{
    Image image = Image.FromFile(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"));
    ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == image.RawFormat.Guid);
    return File(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"), codec.MimeType);
}

View

<img src="@Url.Action("ExibirImagem")"/>

When I try to do this, I get the following error:

  

The process can not access the file because it is being used by another process

What can I do to force the deletion of this image?

    
asked by anonymous 21.05.2015 / 21:06

1 answer

1

The problem occurred because you were opening the image without closing it.

In the code snippet:

public ActionResult ExibirImagem() 
{
    Image image = Image.FromFile(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"));
    ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c = > c.FormatID == image.RawFormat.Guid);
    return File(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"), codec.MimeType);
}

It should look like this:

public ActionResult ExibirImagem() 
{
    string mimeType;
    using(Image image = Image.FromFile(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"))) 
    {
        ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().First(c = > c.FormatID == image.RawFormat.Guid);
        mimeType = codec.MimeType;
    }
    return File(Path.Combine(Server.MapPath("~/Minha/Pasta/"), "foto.jpg"), mimeType);
}
    
25.05.2015 / 14:26