• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 452
  • Last Modified:

Binary input stream to file

I want to read the input stream (HTTP POST to an aspx page) and write it to a file on the web server.  Want it to be binary friendly.  This is my amateur attempt to write the code...

            System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
            System.IO.StreamWriter sw = System.IO.File.WriteAllBytes(appSettings["fileDirectory"] + fileName, sr.ReadToEnd);

It has some type and overloading problems.  Any suggestions?  Thanks a lot.
1 Solution
Bob LearnedCommented:
Ok, so for this ASP.NET 2.0 problem, here is what I would suggest:

      using (BinaryReader br = new BinaryReader(Request.InputStream))

        int length = (int)Request.InputStream.Length;

        byte[] buffer = br.ReadBytes(length);

        File.WriteAllBytes(appSettings["fileDirectory"] + fileName, buffer) ;

1) The using block will Dispose of the reader implicitly at the completion of the block

2) Use a BinaryReader to get the bytes

3) Write the bytes to the file, without the StreamWriter.

jschnei555Author Commented:
Works perfectly.  Clean and simple code too.  Thanks.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

7 new features that'll make your work life better

It’s our mission to create a product that solves the huge challenges you face at work every day. In case you missed it, here are 7 delightful things we've added recently to monday to make it even more awesome.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now