I want to load the image files in a folder then add them to an imagelist then I will assign it to a listview to get thumbnail style on which item I click, it is shown in a picturebox. When I want to delete a file, I make the image property of the imagebox to null then I will remove the image item from listview and imagelist then I proceed to delete the file which I get the error “The process cannot access the file “path to image file” because it is being used by another process.
The code to load the images that fills the imagelist and listview:
private void LoadImages(string path)
{
try
{
imageList = new ImageList() { ColorDepth = ColorDepth.Depth32Bit, ImageSize = new Size(194, 194), TransparentColor = Color.Transparent };
listView.LargeImageList = imageList;
IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
AddImage(file);
}
if (listView.Items.Count > 0)
{
string firstImage = listView.Items[0].ImageKey;
selectedPicBox.Image = Image.FromFile(firstImage);
selectedPicBox.ImageLocation = firstImage;
}
}
catch (Exception ex)
{
Program.EventLog.WriteEntry($"Scan-Loading scans : {ex}", EventLogEntryType.Error, 101);
throw;
}
}
The code that adds images:
imageList.Images.Add(path, Image.FromStream(new MemoryStream(File.ReadAllBytes(path)), true, false));
listView.Items.Add(path, file.Name, path);
The code that deletes the images:
string path = listView.SelectedItems[0].ImageKey;
selectedPicBox.Image = null;
selectedPicBox.ImageLocation = null;
listView.SelectedItems.Clear();
listView.Items.RemoveByKey(path);
imageList.Images[path].Dispose();
imageList.Images.RemoveByKey(path);
File.Delete(path);