0

I have created listview with imagelist and delete function that will delete/remove the file using filename selected on listview.

But I get the error that the file is being used by another process. Below is the code I'm using:

//// Listview with Imagelist
private void listImages()
{
   imageList.View = View.Details;
   imageList.Columns.Add("Images", 650);
   ImageList imgs = new ImageList();
   imgs.ImageSize = new Size(200, 130);

   DirectoryInfo d = new DirectoryInfo(adsFolder);
   FileInfo[] Files = {};

   try
   {
      Files = d.GetFiles("*");

      for (var i = 0; i < Files.Count(); i++)
      {
         imgs.Images.Add(Image.FromFile(Files[i].FullName));
         imageList.Items.Add(Files[i].Name, i);
      }

      imageList.SmallImageList = imgs;
   }

   catch (Exception e)
   {
       MessageBox.Show(e.Message);
   }
}

//// Delete function
private void deleteFile_Click(object sender, EventArgs e)
{
   using (FileStream stream = new FileStream("Selected Image"), FileMode.Open, FileAccess.Read))
   {
      stream.Dispose();
   }

   File.Delete("Selected Image");
}

I have found that the imagelist is causing the error since the image is listed on imagelist. When I remove the imagelist it's working properly. However I want to retain the imagelist on my listview. How can I stop or clear the imagelist so that it's not using the selected image anymore and so that I can proceed on deleting the selected file? I tried using imagelist.clear()but it didn't work.

Richard
  • 439
  • 1
  • 6
  • 25
  • Two ways: clone the image before adding it to the ImageList or dispose of the Bitmap before deleting it. In the second case, the bitmap file will be locked for the time it's referenced. In the first case, never. That `using (FileStream stream (...)` it's hard to understand. – Jimi Apr 02 '19 at 03:41
  • 1) It's not necessary to call `Dispose` when you are using a `using` block for the same disposable. 2) why are you bothering to read the file anyway if you are just going to delete the file in the delete callback? –  Apr 02 '19 at 03:50

1 Answers1

3

Your problem is this line:

imgs.Images.Add(Image.FromFile(Files[i].FullName));

Specifically Image.FromFile is creating an unmanaged bitmap resource that has an open handle to your file.

You will need to Dispose the bitmap you create for your imageList.

If you have the index you can do something like this:

imageList.Images[index].Dispose();
ImageList.Images.RemoveAt(index);
File.Delete(FileName);
halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • I used `imageList.Dispose();` but it didn't work. I also tried using `ImageList.RemoveAt(index);` but there's error saying that ImageList does not contain `RemoveAt`. – Richard Apr 02 '19 at 05:16
  • @richard You dont want to dispose the imagelist, you need to dispose the item in it. please check the documentation, also i have updated my answer – TheGeneral Apr 02 '19 at 05:19