Home > Software design >  Amazon cannot access closed stream
Amazon cannot access closed stream

Time:01-13

I am trying to use amazon s3 libs but somehow can't pass stream to upload data to s3.

At the beginning I was using using statements but then rewrote it to try catch dispose and still I can't even dispose the stream, stream is not null but I get exception when trying to dispose that "cannot access closed stream" on the line streamWriter?.Dispose();

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);

try
{
    try
    {
        await streamWriter.WriteAsync(commandWithMetadata.SerializeToString());
        memoryStream.Seek(0, SeekOrigin.Begin);

        var fileName = GetFileName(command);
        var request = new PutObjectRequest
        {
            BucketName = BucketName,
            Key = fileName,
            InputStream = memoryStream
        };

        await client.PutObjectAsync(request);
    }
    finally
    {
        streamWriter?.Dispose();
    }
}
finally
{
    memoryStream?.Dispose();
}

CodePudding user response:

Try the following calling await streamWriter.FlushAsync(); before await client.PutObjectAsync(request);.

But I think better approach would be:

using (var memoryStream = new MemoryStream())
{
    using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8, leaveOpen: true))
    {
        await streamWriter.WriteAsync(commandWithMetadata.SerializeToString());
    }
    memoryStream.Seek(0, SeekOrigin.Begin);

    //... send
}

By default StreamWriter on dispose tries to flush remining data in buffer and close underlying stream (which seems to be already closed by client.PutObjectAsync(request)) so use leaveOpen: true. Also there is no need to use try-finally-Dispose (and not fully correctly) - there is using statement which will do that for you.

  • Related