Image file blocked by a process in c#

Maurice CHURLET 20 Reputation points
2023-07-21T07:35:19.89+00:00

Good morning,

The following code loads unflowLayoutPanel1.Controls with images from a directory then unloads them before removing them from the directory.

I removed all unnecessary code.

The problem is an error while trying to delete the file which is still in use by another process when it was not before the function call.

I can't find the problem because normally the instruction pictureBox.Image.Dispose(); should free the file.

Can someone help me out as I've been stuck on this issue for several days ?

        private void LoadPhotos(string directory)
        {
            string[] photoFiles = System.IO.Directory.GetFiles(directory, "*.jpg"); // Filtre pour les fichiers images (vous pouvez modifier selon vos besoins)

            try
            {
                flowLayoutPanel1.Controls.Clear();
                foreach (string photoFile in photoFiles)
                {
                    PictureBox pictureBox = new PictureBox();
                    pictureBox.Image = (System.Drawing.Image)System.Drawing.Image.FromFile(photoFile);
                    pictureBox.ImageLocation = photoFile;
                    pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
                    pictureBox.Width = 150;
                    pictureBox.Height = 150;
                    pictureBox.Margin = new Padding(5);
                    flowLayoutPanel1.Controls.Add(pictureBox);
                    System.Windows.Forms.Application.DoEvents();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Une erreur s'est produite lors du chargement des photos : " + ex.Message);
            }

            // Libération des fichiers avant leur effacement
            foreach (PictureBox pictureBox in flowLayoutPanel1.Controls)
            {
                string imageLocation = pictureBox.ImageLocation;
                pictureBox.Image.Dispose();
                pictureBox.Dispose();
                File.Delete(imageLocation);
            }
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,283 questions
{count} votes

Accepted answer
  1. Viorel 119.7K Reputation points
    2023-07-21T08:31:17.5233333+00:00

    Try this:

    var ms = new MemoryStream( File.ReadAllBytes( photoFile ) );
    pictureBox.Image = Image.FromStream( ms );
    pictureBox.Tag = ms;
    File.Delete( photoFile );
    . . .
    

    Do not use ImageLocation. The second loop is not used. If the second loop is needed, the code can be adjusted.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.