Mugen
Mugen

Reputation: 9095

File is being used Exception at Directory.Delete with the folder's path in the message

Hi I'm running the following code:

void bar()
{
    var dirInfo = new DirectoryInfo("C:\foo\folder");
    dirInfo.Delete();
}

And at one point I got the following exception:

System.IO.IOException: The process cannot access the file 'C:\foo\folder' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
at bar()

Two things bother me here:

I called DirectoryInfo's Delete(). Why did I get Directory's Delete() in the stack trace without DirectoryInfo's one?

How come the file that is being used has the same path as my folder? Is this an error in the message? Or was there a different error?

Upvotes: 0

Views: 2510

Answers (1)

Matt Hogan-Jones
Matt Hogan-Jones

Reputation: 3103

To answer the first of your questions, DirectoryInfo.Delete calls Directory.Delete. If you're running in release mode, it's possible the compiler has optimised your code and you're just seeing the underlying call.

Edit: I've just done some tests in VS2013. When my project was a release build compiled for Any CPU I could see the call to DirectoryInfo.Delete before the call to Directory.Delete in the stack trace:

StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive, Boolean throwOnTopLevelDirectoryNotFound)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive, Boolean checkHost)
   at System.IO.DirectoryInfo.Delete()
   at test.Program.Main(String[] args) in c:\Projects\test\Program.cs:line 21

but when I compiled a release build for x64 it showed only the call to Directory.Delete:

StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive, Boolean throwOnTopLevelDirectoryNotFound)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive, Boolean checkHost)
   at test.Program.Main(String[] args) in c:\Projects\test\Program.cs:line 22

It does look like some optimisation is going on (incidentally, the code was unchanged between tests - I'm guessing the change in line number is also related somehow to compiler optimisation).

Have a look at this question - directoryinfo delete vs directory delete

To answer your other question - did you have a file in the directory open in another app? There are many reasons why another process may be doing something to that folder.

Upvotes: 1

Related Questions