Why getting exception The process cannot access the file image0.gif' because it is being used by another process even if I dispose it first ?

Chocolade 516 Reputation points
2021-11-02T18:33:10.697+00:00
private void GenerateAnimatedGifs()
        {
            UnFreezWrapper unfreezWrapper = new UnFreezWrapper();

            checkBoxGetImages = false;
            checkBoxGetAllImages.Checked = false;
            GetImagesFiles();

            for (int i = 0; i < filesSatellite.Length; i++)
            {
                Image img = Image.FromFile(filesSatellite[i]);
                img.Save(filesSatellite[i] + "ConvertedToGif.gif", System.Drawing.Imaging.ImageFormat.Gif);
                img.Dispose();

                File.Delete(filesSatellite[i]);
            }

            GetImagesFiles();

            unfreezWrapper.MakeGIF(filesRadar.ToList(), @"d:\Downloaded Images\Animates Gifs\radanim.gif", 100, true);
            unfreezWrapper.MakeGIF(filesSatellite.ToList(), @"d:\Downloaded Images\Animates Gifs\satanim.gif", 100, true);
        }

In the loop I convert each image to gif save it in other name and then dispose the original image and then trying to delete the original image so only the ConvertedToGif images will left.

but I'm getting the exception is being used by another process on the delete line

File.Delete(filesSatellite[i]);

but isn't the file disposed already ?

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,828 questions
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.
10,239 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2021-11-03T02:07:36.27+00:00

    See if this might work for you

    ImageHelpers.LoadBitmap("Your file name goes here")
    
    
    public static class ImageHelpers
    {
        /// <summary>
        /// Load a clone of an image
        /// </summary>
        /// <param name="fileName">Image file to load</param>
        /// <returns><see cref="Bitmap"/></returns>
        public static Bitmap LoadBitmap(string fileName)
        {
            Bitmap imageClone = null;
            var imageOriginal = Image.FromFile(fileName);
    
            imageClone = new Bitmap(imageOriginal.Width, imageOriginal.Height);
    
            Graphics gr = Graphics.FromImage(imageClone);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed;
            gr.DrawImage(imageOriginal, 0, 0, imageOriginal.Width, imageOriginal.Height);
            gr.Dispose();
            imageOriginal.Dispose();
    
            return imageClone;
        }       
    }
    
    0 comments No comments