Tolga Evcimen
Tolga Evcimen

Reputation: 7352

FileStream is not closed even if it's in a using statement

I have a wcf method like this for uploading file chunks:

public void UploadChunk ( RemoteFileChunk file )
{
    using ( var targetStream = new FileStream("some-path", FileMode.OpenOrCreate, FileAccess.Append, FileShare.None) )
    {
        file.Stream.CopyTo(targetStream);
        file.Stream.Close();
    }
}

Which is pretty basic stuff. But what happens on an exceptional case is pretty strange. Exceptional case steps:

  1. Start uploading the chunk
  2. Loose internet connection during upload
  3. UploadChunk methods throws CommunicationException because of the lost internet connection
  4. ...wait for internet connection to come back
  5. Start uploading the last chunk again
  6. Boom!!! Throws the exception below:

The process cannot access the file 'some-path' because it is being used by another process.

I know that file is not touched by anyone else, which leads me that the file was left open on the last call when connection lost. But as far as I know using statement should have closed the FileStream, however in this case it didn't.

What I might be missing here?

Btw, I have another question which I'm guessing is caused by the same problem that I'm not aware of. Maybe it can lead you guys to some clue.

Upvotes: 3

Views: 1073

Answers (1)

Polyfun
Polyfun

Reputation: 9639

What is RemoteFileChunk? My guess is that it is RemoteFileChunk that has the file open. You have not shown any code for RemoteFileChunk which demonstrates that it will automatically close its Stream when an exception occurs. This should work (although it might be better to encapsulate the close within RemoteFileChunk itself):

public void UploadChunk ( RemoteFileChunk file )
{
    using ( var targetStream = new FileStream("some-path", FileMode.OpenOrCreate, FileAccess.Append, FileShare.None) )
    {
        try
        {
            file.Stream.CopyTo(targetStream);
        }
        finally
        {
            file.Stream.Close();
        }
    }
}

Upvotes: 1

Related Questions