views:

108

answers:

2

Hello all,

In my listview I show thumbnails of small images in a certain folder. I setup the listview as follows:

var imageList = new ImageList();
foreach (var fileInfo in dir.GetFiles())
{
    try
    {
        var image = Image.FromFile(fileInfo.FullName);
        imageList.Images.Add(image);
    }
    catch
    {
        Console.WriteLine("error");
    }
}

listView.View = View.LargeIcon;
imageList.ImageSize = new Size(64, 64);
listView.LargeImageList = imageList;

for (int j = 0; j < imageList.Images.Count; j++)
{
    var item = new ListViewItem {ImageIndex = j, Text = "blabla"};
    listView.Items.Add(item);
}

The user can rightclick on an image in the listview to remove it. I remove it from the listview and then I want to delete this image from the folder. Now I get the error that the file is in use. Of course this is logical since the imagelist is using the file.

I tried to first remove the image from the imagelist, but I keep on having the file lock.

Can somebody tell me what I am doing wrong?

Thanks!

+1  A: 

The image will need to be disposed of before it will unlock the file. Try calling Dispose on the image object after you remove it from the image list.

So long as you have a reference to the image object and the GC hasn't collected it, it will keep the lock. Calling Dispose should force it to give up its handle and cause the file to be unlocked.

You also have to make sure that the app didn't CopyHandle or otherwise get a second reference to the image resource before doing this.

Frank Krueger
+3  A: 
SLaks
That worked immediatly! Thanks a lot
Enrico
@Enrico: this is very wasteful of machine resources. You simply forgot to call image.Dispose() after adding it to the ImageList.
Hans Passant
@Hans: Does the `ImageList` make a copy of the image?
SLaks
It clones the bitmap to match the size and color depth of the ImageList.
Hans Passant
Then you're right; I'll edit.
SLaks