I have several images binded to an ObservableCollection for a listview that I need to delete when I close the window and and generate again when I open the window again. Unfortunately, whenever I try to delete the images after closing the window I get the error "The process cannot access the file because it is being used by another process." My question is: How can I free the images from all processes when I close the window?
Here is the code for my WPF window:
ObservableCollection<ModuleView> otherModules = new ObservableCollection<ModuleView>();
public ValidationWindow()
{
Closed += WindowClosed;
InitializeComponent();
// Populate List viewer with ObservableCollection
string resourceFolder = //path to resource folder
for (int i = 1; i < nClusters - 1; i++)
{
if (i == currentCluster) continue;
ModuleView obj = new ModuleView() { Module = i, ModuleText = "Module " + i, ImagePath = resourceFolder + "/" + i + ".png" };
otherModules.Add(obj);
}
moduleViewer.ItemsSource = otherModules;
}
private void WindowClosed(object sender, EventArgs e)
{
otherModules.Clear();
Close();
}
This is my custom object for the Observable collection:
class ModuleView
{
public int Module { get; set; }
public string ModuleText { get; set; }
public string ImagePath { get; set; }
}
And this is where I open my window and try to delete the files; this code is being called from a button:
// Delete image files
string[] pngfiles = Directory.GetFiles(resourcesFolder, "*.png", SearchOption.TopDirectoryOnly);
foreach (var file in pngfiles)
File.Delete(file); // ERROR HAPPENS HERE
// Code to generate the images again
// Open Validation Windows
ValidationWindow myForm = new ValidationWindow();
myForm.Show();
The error happens when I try to delete the files. I'm not sure what to do. I've tried clearing the Garbage Collector, clearing the Observable Collection list while closing the window but the error persists.