0
votes

I'm fairly new at working with streams, and I'm testing web app uploads to Amazon Web Services using the SDK APIs. An error is generated during this process that says the FileStream is null. I've tried using the Put instead of TransferUtility and read all of the AWS documentation, but uploads seem to only be explained from a path instead of from a web upload. Does anyone see why the FileStream is null and the save is not working? Thanks in advance!

using (var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest1))
{
    //Save File to Bucket
    using (FileStream txtFileStream = UploadedFile.InputStream as FileStream)
    {
        try
        {
            TransferUtility fileTransferUtility = new TransferUtility();
            fileTransferUtility.Upload(txtFileStream, bucketLocation, UploadedFile.FileName);
        }
        catch (Exception e)
        {
            e.Message.ToString();//txtFileStream is null!
        }
    }
}
1
I'm guessing your cast fails. What is UploadedFile.InputStream? - Jonesopolis
Thanks for the response. UploadedFile is the .txt file that the user uploads from the website, and I just used the HttpPostedFileBase.InputStream for the FileStream. - jle

1 Answers

2
votes

When you cast using as, it won't throw an exception, but fail silently, and return null. When you're using as, you're saying

sometimes this could fail, and I'm prepared to handle that.

Generally you'd do a null check:

FileStream txtFileStream = UploadedFile.InputStream as FileStream
if(txtFileStream != null)
{
    using(txtFileStream)
    {
        //.....
    }
}

if you are sure that this should be a FileStream, you should use a direct cast. A direct cast will throw an exception if it fails. That's like saying

this should always be this type, if it isn't, something is horribly wrong and I can't continue.

Do that with:

using(FileStream txtFileStream = (FileStream)UploadedFile.InputStream)
{

}

For your question, you need to figure out what why your cast is failing.