Cannot delete image file that is displayed in the list.

In my list, I show thumbnails of small images in a specific folder. I configure 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 right-click on the image in the list to delete it. I delete it from the list and then want to remove this image from the folder. Now I get an error that the file is being used. Of course, this is logical, since imagelist uses the file.

I tried to remove the image from imagelist first, but I continue to store the file.

Can someone tell me what I'm doing wrong?

Thanks!

+4
source share
3 answers

You need to load the file into a MemoryStream, for example:

 var image = Image.FromStream(new MemoryStream(File.ReadAllBytes(fileInfo.FullName))); 

Thus, the file will be read only once and will not be locked.

EDIT

You upload images to ImageList.
Since ImageList makes copies of its images, you should simply delete the originals right away, for example:

 using (var image = Image.FromFile(fileInfo.FullName)) imageList.Images.Add(image); 
+5
source

The image must be deleted before it unlocks the file. Try calling Dispose on the image object after removing it from the image list.

As long as you have a reference to the image object, and the GC has not assembled it, it will retain the lock. A call to Dispose should force it to abandon the handle and cause the file to be unlocked.

You should also make sure that the application did not execute CopyHandle or otherwise received a second link to the image resource before doing this.

+1
source

Use GetThumbnailImage and then delete the image:

 var image = Image.FromFile(fileN); Image imgThumb = image.GetThumbnailImage(100, 100, null, new IntPtr()); imageList1.Images.Add(imgThumb); image.Dispose(); listView1.LargeImageList = imageList1; 

Now you can delete the file:

 File.Delete(FileN); 
0
source

Source: https://habr.com/ru/post/1307588/


All Articles