FileStream does not close even if used in statement

I have a wcf method to download chunks of a file:

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();
    }
}

      

This is pretty basic stuff. But what happens in the exceptional case is rather strange. Exceptional steps:

  • Start downloading snippet
  • Free internet connection while downloading.
  • UploadChunk Methods Throwing Out Due To CommunicationException

    Lost Internet Connection
  • ... wait for the internet connection to come back.
  • Start downloading the last snippet
  • Boom !!! Throws the following exception:

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

I know the file hasn't been touched by anyone else, which leads me to the file being left open on the last call when the connection is lost. But as far as I know, the operator using

should have closed FileStream

, but in this case he did not.

What am I missing here?

Btw, I have another question which I assume is caused by the same problem that I am not aware of. Maybe this can lead you to some clues.

+3


source to share


1 answer


What is RemoteFileChunk? I am assuming it is the RemoteFileChunk that has the file open. You haven't provided any code for RemoteFileChunk that demonstrates that it automatically closes its thread when an exception is thrown. This should work (although it would be better to encapsulate the closure inside the 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();
        }
    }
}

      

+1


source







All Articles