Reputation: 17
I have troubleshoot with delete picture in my application, I used foreach to delete file in folder.
I used Headless skype login in my applicaton with query contact name and contact's photos After login succeed, but I have problem when I closed my app ,I wanna delete all contact's photos in my app's folder .See the code to delete:
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var applicationDirectory = System.IO.Path.GetDirectoryName(assemblyLocation);
var imagesDirectory = System.IO.Path.Combine(applicationDirectory, "img");
var contact_photo = Directory.EnumerateFiles(imagesDirectory,
"*.jpg",SearchOption.TopDirectoryOnly);
if (contact_photo != null)
{
foreach (var photo in contact_photo)
{
Console.WriteLine(photo);
File.Delete(photo);
}
}
Error Message:
The process cannot access the file 'C:\Users\...\mypicture.jpg'
because it is being used by another process.
Help me please!
Upvotes: 1
Views: 622
Reputation: 63203
Before deleting the images, did you review your usage of those images?
Other parts of your WPF app may lock them when you don't notice,
BitmapImage in WPF does lock file
Upvotes: 0
Reputation: 5627
Refer to this answer https://stackoverflow.com/a/1025446/988830
The file is used by another process and you have to make sure the process which has hold the file has released it. If it is not in your control then you need to you try catch block to avoid exception and you cannot do more than that.
try
{
//Delete file
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
Upvotes: 1