1

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!

vyegorov
  • 21,787
  • 7
  • 59
  • 73

2 Answers2

1

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());
}
Community
  • 1
  • 1
om471987
  • 5,398
  • 5
  • 32
  • 40
  • Thank for your answer, when I try to follow you the error show in console, But I don't know exactly, why I can't delete when I login corrected user name and password in Skype. For me I'm not sure , but I think because of I using DispatcherTimer() in MainWindows to query contact loop in 5 seconds. So maybe problem with DsspatcherTimer when process delete that photo. How do you think about this process? Problem with Skype runtime or DispactureTimer when I delete ?. Any idea pleas ! – user1379210 May 12 '12 at 03:26
0

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

Community
  • 1
  • 1
Lex Li
  • 60,503
  • 9
  • 116
  • 147