Search code examples
c#.netamazon-web-servicesaws-sdkhttppostedfilebase

HttpPostedFileBase.InputStream Cast to Stream Silently Fails


I'm new to working with streams and having difficulty uploading a text file from a web app to AWS. Specifically, a cast on the HttpPostedFileBase.InputStream to (Stream) doesn't throw an error, but the resulting Stream contains no data even though it passes a null check, so the upload "works" but always results in a blank text document. I couldn't find this question on a search of SO, the code is duplicated from the AWS SDK examples, and the input stream has been copied to a MemoryStream with a starting position set to zero, so I'm at a dead end here. Does anyone know why this isn't working and how to fix it? Thanks in advance!

using (var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest1))
{
    Stream saveableStream = new MemoryStream();
    using (Stream source = (Stream)UploadedHttpFileBase.InputStream)
    {
        source.Position = 0;
        source.CopyTo(saveableStream);//Results in no data!
    }
    saveableStream.Position = 0;
    //Save File to Bucket                                        
    try
    {
        PutObjectRequest request = new PutObjectRequest
        {
            BucketName = bucketLocation,
            Key = UploadedHttpFileBase.FileName, 
            InputStream = saveableStream
        };
        PutObjectResponse response = client.PutObject(request);
    }
    catch (Exception e)
    {
        e.Message.ToString();
    }
}

Solution

  • The answer here had something to do with nesting and nothing inherently to do with the posted code. I'm not completely sure how the streams work, but there was a StreamReader at the start of the question's method that checked an initial ReadLine's value to know whether or not to save. When I moved this question's code out from the while loop doing the ReadLines, the upload worked. After reorganizing the validation without the need for the nested Stream or MemoryStream in the question, everything works as it's supposed to.