Hello:
I have one WinForms App target .NET 5.0 on Windows 10.
There are around 100 PNG format files in one folder, I have to use one PictureBox to view one PNG file one at a time, and some PNG files will be deleted, as their quality is too bad.
So, I added one ListView to go through all the PNG files, and one button (ButtonDelete) to delete the currently selected PNG file.
But I don’t know how I can delete the PNG file, as it is being used by image = image.FromFile().
The following is part of my C# code:
private void ListViewImage_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ListViewImage.SelectedItems.Count >= 1)
{
string image_file1 = ListViewImage.SelectedItems[0].Text;
Image source_bmp = Image.FromFile(image);
PictureBoxImage0.Invoke((MethodInvoker)delegate
{ PictureBoxImage0.Image = source_bmp; });
}
}
}
catch (InvalidOperationException ex)
{
Debug.Print(ex.Message);
}
}
private async void ButtonDelete_Click(object sender, EventArgs e)
{
try
{
PictureBoxImage0.Invoke((MethodInvoker)delegate { PictureBoxImage0.Dispose(); });
await Task.Delay(2000);
string png_file1 = @"C:\Images\1.png";
// Image source_bmp = Image.FromFile(png_file1);
// source_bmp.Dispose();
File.Delete(png_file1);
}
catch (IOException ex)
{
Debug.Print("[ButtonDelete_Click]: " + ex.Message);
}
}
When I run my code, I got the following error:
[ButtonDelete_Click]: The process cannot access the file 'C:\Images\1.png' because it is being used by another process.
I know the file is used by this statement in ListViewImage_SelectedIndexChanged:
string image_file1 = ListViewImage.SelectedItems[0].Text;
Image source_bmp = Image.FromFile(image);
But how I can find which process is accessing the file, and how I can kill the process?
I find there is a new System.Management name space (Version 5.0.0), but I can’t find any good example on how to find the process using the file, then kill the process, so I can delete the PNG file.
Please advise!