Search code examples
c#winformsdelete-fileimagelist

How to delete file using windows form c#


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.


Solution

  • 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);