Pages - Menu

C# .Net Cannot close stream until all bytes are written.


We are dealing with the Stream class in .Net and run into an inner exception of "Cannot close stream until all bytes are written."


    using (var ms = new MemoryStream())

        // Create a PutObject request
        var request = new PutObjectRequest
            BucketName = bucket,
            Key = key,
            InputStream = ms

        // Call S3 ....
catch (Exception ex)
    _logger.Error(ex.Message, ex);
    throw ex;

By using the keyword using, we are expecting .Net will handle the close connection for us.

Rather than unable to close the stream, it was actually a problem where the position of the MemoryStream was at the end after the XElement.Save(). We need to manually reset the position of the stream to zero, so that it can be written to the PutObjectRequest object.

ms.Position = 0;

No comments:

Post a comment