Amazon.S3.AmazonS3Client PutObject “Cannot close stream until all bytes are written”

The AWS .NET SDK in my opinion is horrible, and poorly documented. Below is an issue i had that was very hard to trouble shoot so thought i would post about it.

The below code was giving me this exception

System.Net.WebException: The request was aborted: The request was canceled. —> System.IO.IOException: Cannot close stream until all bytes are written. at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting) — End of inner exception stack trace — at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting) at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState) at System.Net.ConnectStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at Amazon.S3.AmazonS3Client.getRequestStreamCallback[T](IAsyncResult result)


using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(awsAccessKey, awsSecretKey))
 {
 var s3Key = awsEticketFolder + eticketFileName;
 var objReq = new PutObjectRequest();
 objReq.WithInputStream(eticketFileStream);
objReq.WithBucketName(awsBucketName);
 objReq.WithKey(s3Key);
 objReq.WithContentType(mimeType);
 objReq.CannedACL = S3CannedACL.PublicRead;
 objReq.StorageClass = S3StorageClass.Standard;

client.PutObject(objReq);
 }

Was only getting it on large files.

It appears that under the hood, the library is timing out and closing the connection before it was complete hence causing this error.

I have been told however that this might only occur on memorystream objects, and that filestreams might actually get a timeout error, I haven’t verified this though.

The solution?


objReq.WithTimeout(60*60*1000);

Adding a time out to the object of 1 hour allows my big files to upload successfully.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s