How to use ASP.NET FileUpload’s PostedFile.InputStream

This week I started working on a new file uploader for the company website admin. The current version uses the HttpPostedFile SaveAs method to save the file to a temporary directory before uploading to the web server using FTP. I decided to make the new version use HttpPostedFile’s InputStream property to transfer the file in one go instead.

Seemed straightforward enough, but I hit a snag.

My first attempt at the code to upload the file looked something like this:

It seemed to work, but it turned out while the image file I was uploading ended up being the right size, the image was corrupted.

After reading a bunch of MSDN articles, forum posts, blog posts and StackOverflow answers, I discovered that the seek position needed to be reset before reading the stream.

So the code needed to be like this: