Reputation: 6390
I've got a bit of code in a product I am supporting that copies files:
using(System.IO.FileStream sourceFS = new System.IO.FileStream(sourcePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
{
using(System.IO.FileStream targetFS = new System.IO.FileStream(targetPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read))
{
while((read = sourceFS.Read(buffer, 0, buffer.Length)) > 0)
{
targetFS.Write(buffer, 0, read);
}
targetFS.Flush();
targetFS.Close();
}
sourceFS.Close();
}
Unfortunately, the users are reporting an exception informing us that the destination file is in use by another process. I've asked if there is a chance that someone has the file open (it's an Excel file) - apparently not...
So, I put the thinking cap on... Is it possible we are leaving the destination file with a file lock against it? The only way I can see for targetFS not to be closed would be require both:
This sounded unlikely to me, but ever curious I used dotPeek from JetBrains to disassemble the Dispose method on the FileStream class - which doesn't seem to do all that much really - I'm guessing its "close" behaviour is provided by disposing of the handle...
In essence though - the question is this - can anyone spot how this might be leaving a file with a lock against it?
Upvotes: 0
Views: 6656
Reputation: 171246
Look elsewhere. This code is fine. Not sure what else to say about it. using
is meant for exactly this use case - failsafe disposal.
Investigate using Process Explorer which process is holding a handle to the file in question.
Upvotes: 2