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):
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:
Hope this helps someone see the wood from the trees and not waste time looking for a simple mistake.