File.Create and the mysterious IOException
Posted by Garry Shutler in Extension methods, Gotchas
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):
{
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:
{
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.
This entry was posted on at Thursday, June 05, 2008 and is filed under Extension methods, Gotchas. You can follow any responses to this entry through the RSS 2.0. You can leave a response.
