I have moved my active blog over to tumblr. I've maintained this blog for reference but will be posting to http://www.robustsoftware.co.uk instead. I've pointed my Feedburner feed to tumblr so if you're subscribed already you should already have switched with me.

File.Create and the mysterious IOException

I was putting together a bunch of unit tests today for a program that's managing the transfer, etc. of a bunch of files. I created an extension method to make it easy to add empty files to directories for my tests (code requires the System.IO namespace to be imported):

public static void CreateEmptyFile(this DirectoryInfo directory, string fileName)
{
    File.Create(Path.Combine(directory.FullName, fileName));
}

However, everything was going fine with my tests until I started trying to move files about. Whenever I wanted to move a file I would get an IOException with the message "The file is already in use". My files were being created as I expected, just I could not move them without an exception being thrown. Going over and over the code I could not see where the problem is coming from.

Eventually after bashing my head against a wall for a while I decided to go over everything from the beginning. What I had missed is that File.Create is not a method but a function which returns a FileStream. So the problem was that this FileStream was left hanging around and so I could not do anything with the file.

Once I had realised that the fix was easy, close the stream:

public static void CreateEmptyFile(this DirectoryInfo directory, string fileName)
{
    File.Create(Path.Combine(directory.FullName, fileName)).Close();
}

Hope this helps someone see the wood from the trees and not waste time looking for a simple mistake.