Error trying to erase image file?

Asked

Viewed 528 times

0

I’m trying to get an image update on a criminal record. When I do this update I want to change the existing image to the new update image.

That’s why I’m using the File.Exists and the File.Delete where I check if an image already exists and if it exists I delete and replace it with the new image.

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

The exception is

The process cannot access the file 'C: xampp htdocs Iguanabarws app webroot img categorias 3.jpg' because it is being used by Another process.`

How can I solve 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;         
}
  • How are you loading this image to Picturebox? You can put the code for this function in the question?

  • Probably you must be facing permission issues to the directory where the image is stored, try to do the same by accessing in another directory that is without access restrictions.

  • 1

    @I’m sorry to intrude, but it probably has nothing to do with this. His problem is that the image may be referenced in Picturebox

  • Opa @jbueno, no problem, we are here to help the community.

  • @jbueno to add the image to the Picturebox do so: pictureBox1.Image = Image.FromFile(PATH_FOLDER + this.categoria.imagem);

2 answers

1

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

Who is using the image is the PictureBox and for it to be possible to delete this image you should call the method Dispose() of property Image of PictureBox. Take 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 whether a particular file exists before trying to delete it.

0

Solved, I found the solution here: https://support.microsoft.com/en-us/kb/309482 . How @jbueno suggested the image was locked in pictureBox. Thanks @jbueno

to resolve 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);
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.