Error trying to delete image file? [duplicate]

0

I'm trying to do an image update on a cadaster. When I do this update I want to change the existing image to the new update image.

For this I am using File.Exists and File.Delete where I check if an image already exists and if it is deleted and replaced by the new image.

The problem is that this always returns me an exception and does not delete the existing image.

The exception is

  

The process can not access the file 'C: \ xampp \ htdocs \ IguanaBarWS \ app \ webroot \ img \ categories \ 3.jpg' because it is being used by another process. '

How can I resolve this problem?

I'm trying like this.

private void saveImageCategoria(String imgName) 
{
    Image img = pictureBox1.Image;            
    Image imgResize = ResizeImage.getResizeImage(img, new Size(50,50));
    if (File.Exists(PATH_FOLDER + imgName)) 
    {
        File.Delete(PATH_FOLDER + imgName);
    }   
    imgResize.Save(PATH_FOLDER + imgName);
    pictureBox1.Image = null;         
}
    
asked by anonymous 22.03.2016 / 07:40

2 answers

1

This is because, with the forgiveness of the infamous pun, the image is being used by another process.

Who is using the image is PictureBox and in order to be able to delete this image you must call the Dispose() method of the Image property of the PictureBox . Here's an example:

private void ExcluirImagem() 
{
    pictureBox1.Image.Dispose();

    File.Delete("Caminho/Da/Imagem.png");
}

An important detail is that you do not need to check if a particular file exists before attempting to delete it.

    
22.03.2016 / 16:19
0

Solved, I found the solution here: link . As @jbueno suggested the image was locked in the pictureBox. Thanks @jbueno

To solve it I did so.

//set image pictureBox
FileStream fs = new FileStream(PATH_FOLDER + this.categoria.imagem, FileMode.Open, FileAccess.Read);
            pictureBox1.Image = Image.FromStream(fs);
            fs.Close();

//delete image
if (File.Exists(PATH_FOLDER + imgName)) {
                File.Delete(PATH_FOLDER + imgName);
            }
    
22.03.2016 / 16:21