0

An unhandled exception of type System.IO.IOException occurred in mscorlib.dll

Additional information: The process cannot access the file pathOfMyFile because it is being used by another process.

This is the error I get when reaching File.Delete My code looks like this:

File.Copy(frompath, topath1);
File.Copy(frompath, topath2);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(frompath);

frompath is a path to a .png image. What can I do to make this work?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 5
    `topath1`, `topath2` and `topath` are three different variables. Your application, or another application, still holds a lock on the file pointed to by `topath`. Show all relevant code. – CodeCaster Oct 14 '15 at 16:00
  • 1
    Did you mean to delete *frompath*? I'm assuming you aren't trying to copy a file just to turn around and delete the copy you just made. – aquinas Oct 14 '15 at 16:01
  • Yes, i've miswritten it –  Oct 14 '15 at 16:03
  • Can you share some more relevant details and your prior research in your question? What else do you do with the file in `frompath`? [Do you have a virus scanner](http://stackoverflow.com/questions/603444/file-copy-locks-source-file-after-completion)? Who holds the lock according to a tool that can tell you this, like Unlocker? – CodeCaster Oct 14 '15 at 16:04
  • Can you reproduce this in a brand new program? E.g., you put this into a new console app, give it a path, and it fails? Also you say, "can't delete *after* copy." Are you saying if you remove the two File.Copy lines then you *can* delete? – aquinas Oct 14 '15 at 16:05
  • there isnt enough code to determine what could the possible error. I presume the file is not closed so there fore cannot be deleted. Try File.Create(frompath).Close() before doing File.Delete – Raziel Oct 14 '15 at 16:06
  • Yes, i have Kaspersky Internet Security 2016. Tried disabling protection, but the error still occurs. –  Oct 14 '15 at 16:06
  • Code doesn't work if i comment out the copy lines.... now i'll check in console –  Oct 14 '15 at 16:09

1 Answers1

0

First you can remove the two garbage collection calls as they will be processed automatically.

If the copy is simply taking time to complete and the file system to release the handle, you can attempt repeated deletes until it works. You could ignore IOExceptions but make sure to handle other types.

while (true)
{
    Thread.Sleep(50);

    try
    {
        File.Delete(frompath);
        break;
    }
    catch (IOException)
    {
        // Ignore IO exceptions
    }
    catch (Exception)
    {
        // Handle other exceptions
    }
}
Adam Milecki
  • 1,738
  • 10
  • 15
  • According to http://stackoverflow.com/a/2186775/2131092 the main thread is blocked by File.Copy until the copy completes. So it shouldn't be the copy process that is locking the file. – Andy Nichols Oct 14 '15 at 16:17