chopperfield
chopperfield

Reputation: 567

delete folder but the process cannot access the file because being used

so i made a simple project where when i click a button the picture edit get an image from a folder file, but when i want to delete the folder that contains the image, it gives me an error. the code as following

 private void button1_Click(object sender, EventArgs e)
    {
        string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
        pictureEdit1.Image = Image.FromFile(pathx);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string dir = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage";
        try {
            if (Directory.Exists(dir))
            {
                //////give me an error in here///////
                Directory.Delete(dir, true);
            }
            else
            {
                MessageBox.Show("folder not found");
            }
        }
        catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
        }

    }

enter image description here

the purpose of this, is in my main project, for cache purpose. so i get an image from a certain folder after coping it from server to local. and when i want to close the main project i need to clear the cache or folder

Update

which is better alternate 1 or alternate 2 (to dispose)

   private void button1_Click(object sender, EventArgs e)
    {
        string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";

        //alternate1
        using (FileStream stream = new FileStream(pathx, FileMode.Open, FileAccess.Read))
        {
            pictureEdit1.Image = Image.FromStream(stream);
            //stream.Dispose();
        }

        //alternate2
        //Image img = new Bitmap(pathx);
        //pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
        //img.Dispose();

    }

Upvotes: 0

Views: 680

Answers (1)

Lusid
Lusid

Reputation: 4528

The documentation on System.Drawing.Bitmap (http://msdn.microsoft.com/en-us/library/0cbhe98f.aspx) says:

The file remains locked until the Bitmap is disposed.

To get around this, you should replace this line:

pictureEdit1.Image = Image.FromFile(pathx);

With this:

Image img = new Bitmap(pathx);
pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
img.Dispose();

This should load the Bitmap only long enough to create a thumbnail version of the image for use in the PictureBox control, then dispose of it immediately, releasing the lock on the file but still displaying the image on the screen.

Hope this helps!

Edit: Here's the version using using that does the same thing:

using (Image img = new Bitmap(pathx)) {
  pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
}

Upvotes: 1

Related Questions