0

researched many topics about this exception, no luck. my simple code:

            string t = Path.GetTempFileName();
            t = t.Remove(t.Length - 11, 11);
            var q = Directory.EnumerateFiles(t, "tmp????.tmp");

            var f = q.ToList();
            for (int i = 0; i < q.Count(); i++)
            {
                //      if (Helper.CanReadFile(f[i]))
                try
                {
                    File.Delete(f[i]);
                }
                catch (IOException)
                {

                    break;
                }

            }

I ran this code in Closing event of mainwindow. So it deletes several files, gets into exception, then to "break" statement, and then.. somewhere. Just freezes and pausing debugger leads to nothing. I tried several pieces of code to find whether the file is used before deletion, but it gets an exception inside this code (like Helper.CanReadFile) and halts program flow there. I dont really have to delete all files, but I need to stop that freezing. How can I work with this exception so that wont freeze my program?

some edit with breakpoints and info for most of them.

1) got an exception https://i.stack.imgur.com/tokgy.jpg

2) first step from it, nothing much https://i.stack.imgur.com/ZBebU.jpg

3) went back to dispose https://i.stack.imgur.com/M04pZ.jpg

4) went back to event method https://i.stack.imgur.com/1sWOv.jpg

5) which was called from onclose https://i.stack.imgur.com/sLe9e.jpg

6) after that it loops here for a while (I use global hotkey) http://imgur.com/a/0qjdf it goes off after ~10 loops with msg = 130. and my program closes fine if I remove file deletion part.

7) Freezed part (no code is running message) http://imgur.com/a/WeEGj

nufflee
  • 39
  • 2
  • 9
Michael Snytko
  • 327
  • 3
  • 13
  • " then.. somewhere". You must investigate. Place a breakpoint to the break statement, then go step by step in the debugger – g.pickardou Nov 24 '16 at 11:45
  • 1
    what is the break statement for anyways? do you really want to stop deleting all files just because deleting any failed? – nozzleman Nov 24 '16 at 11:48
  • @nozzleman: you are right indeed. We can not delete a specific file, it does not mean to skip all the remaining... – g.pickardou Nov 24 '16 at 11:50
  • 1
    The [Closing event is deprecated](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.closing(v=vs.110).aspx). Use FormClosing instead. – Thomas Weller Nov 24 '16 at 11:57
  • 1
    The method you show us has no start and no end. How are we supposed to know what happens after that? – Thomas Weller Nov 24 '16 at 11:58
  • Start using meaningful names for your variables! Learn about naming conventions. – FCin Nov 24 '16 at 12:13
  • First of all what about all other `Exceptions` ? Catch `Exception` too. You can have an unlimited number of `catch` clauses ! `catch (IOException) { //IO-Error } catch (NotImplementedException) { //NotImplemented } catch (Exception) {//AnyOtherException}` – Felix D. Nov 24 '16 at 12:17

1 Answers1

-1

When deleting files you can try this:

To run this code on a background Thread you can do several things:

Change to private async Task DeleteAllTempFiles() and call it without await !

OR

new Thread(() => { DeleteAllTempFiles(); }).Start();

private void DeleteAllTempFiles()
{
   try
   {
       //Get the temp Path
       DirectoryInfo tempDir = new DirectoryInfo(Path.GetTempPath());
       //Get all matching files
       List<FileInfo> tempFiles = tempDir.GetFiles("tmp????.tmp", SearchOption.AllDirectories).ToList();

       //Collect all files that fail to delete
       List<FileInfo> cannotDelete = new List<FileInfo>();

       //Delete Files:
       DeleteFiles(tempFiles, out cannotDelete);

       //Show what failed (and retry or whatever)
       string message = "Cannot delete the following file(s):";
       cannotDelete.ForEach(file => message += "{file.FullName}{Environment.NewLine}");
       MessageBox.Show(message, "Result");
   }
   catch (Exception ex)
   {
       Debug.Fail(ex.Message);
   }
}

private void DeleteFiles(List<FileInfo> filesToDelete, out List<FileInfo> failedToDelete)
{
   foreach(FileInfo file in filesToDelete)
   {   
      try
      {
         file.Delete();
      }
      catch (IOException ioEx)
      {
         failedToDelete?.Add(file); //<-- Check if failedToDelete != null !!!
         //This will always happen.
         //Since its not "hard fail" you should log it but keep goin !
         //MessageBox.Show($"IO-Exception: {ioEx.Message}");
      }
      catch (Exception ex)
      {
         MessageBox.Show($"Exception: {ex.Message}");
      }
   }
}

If you want to work with the files you can't delete you can process them with this: How do I find out which process is locking a file using .NET?

For a fast check what locks your files you can use: OpenedFilesView or Windows Sysinternals Process Explorer

Maybe you can try to set some attributes... Maybe you can get access with this:

enter image description here

Sorry for the bad size of the image ..

Community
  • 1
  • 1
Felix D.
  • 4,811
  • 8
  • 38
  • 72
  • ok, it tries to delete files, cant delete 3 of them, shows the Msgbox with ioexception infos ( this line -> //MessageBox.Show($"IO-Exception: {ioEx.Message}");), then shows result with 3 names, then I have the screen as this http://imgur.com/a/WeEGj . I feel like some job with that un-deleted file is not done properly, but no idea what exactly. – Michael Snytko Nov 24 '16 at 13:05
  • ok I pasted the code from your link, it shows that only my program is using the file. like that: foreach (var fileInfo in outList) { var z = FileUtil.WhoIsLocking(fileInfo.FullName); string t = ""; z.ForEach(pr => t+= pr.ProcessName); MessageBox.Show(t); } I get shown "myProgramName.vshost" – Michael Snytko Nov 24 '16 at 13:35
  • Alright. But why do you want to delete files Visual Studio is creating **temporary** while debuggin ? Its like sabotating your own program ... – Felix D. Nov 24 '16 at 13:37
  • its my own files :) .vshost just clarifies that the process is launched from visual studio. I create them during the work of my program and want to delete afterwards. Anyway, I added disposal of one object and looks like it works now, but I still dont know how to properly handle such ioexception and why the program freezes. – Michael Snytko Nov 24 '16 at 13:50
  • The program freezes when doing long taking executions on UI-Thread. `GetFiles()` can take a while when SerachOption.AllDirectories is on. The more subDirectories you got the longer it can take. You can use a Thread to run it in the background. – Felix D. Nov 24 '16 at 13:53