Almazini
Almazini

Reputation: 1873

C# unload image from imagebox

I have a method whit the following logic:

  1. I delete all files from input and output folders
  2. user selects an initial picture
  3. this pictures as being assigned to imageBox1
  4. picture is being copied to the folder input
  5. magic happens to picture and I put it to the folder output
  6. new picture from output is beign assigned to imageBox2

Here is where problem starts. When users wants to repeat operation imagebox1 and imagebox2 do have pictures assigned to them. And the step #0 failswith error

The process cannot access the file '03933.tiff' because it is being used by another process.

What I was trying is :

 private void CopyImage_Click(object sender, EventArgs e)
        {
            string currentPath = Directory.GetCurrentDirectory();
            string pathInput = currentPath + "\\Input";
            string pathOutput = currentPath + "\\Output";


               if (pictureBoxInput.Image != null) { 
                pictureBoxInput.Image = null;
                pictureBoxInput.Dispose();
                }

               if (pictureBoxOutput.Image != null) { 
            pictureBoxOutput.Image = null;
            pictureBoxOutput.Dispose();
            }



            System.IO.DirectoryInfo di = new DirectoryInfo(pathInput + "\\");

            foreach (FileInfo file in di.GetFiles())
            {
                file.Delete();
            }

            System.IO.DirectoryInfo dia = new DirectoryInfo(pathOutput + "\\");
            foreach (FileInfo file in dia.GetFiles())
            {
                file.Delete();
            }

But still having the same error when program tries to delete files.

Upvotes: 1

Views: 446

Answers (1)

mjwills
mjwills

Reputation: 23975

I would suggest changing:

if (pictureBoxInput.Image != null) { 
    pictureBoxInput.Image = null;
    pictureBoxInput.Dispose();
}

to:

if (pictureBoxInput.Image != null) { 
    var existingFile = pictureBoxInput.Image;
    pictureBoxInput.Image = null;
    existingFile?.Dispose();
}

and the same for pictureBoxOutput

The issue is that your existing code is disposing the wrong thing - you are disposing the PictureBox rather than the Image (and the Image is the thing that is holding the file lock).

Upvotes: 1

Related Questions