How to download memorystream to a file?

前端 未结 4 2002
半阙折子戏
半阙折子戏 2020-12-10 04:04

I\'m using the below sample code for writing and downloading a memory stream to a file in C#.

MemoryStream memoryStream = new MemoryStream();
TextWriter tex         


        
4条回答
  •  不知归路
    2020-12-10 04:42

    You are doing something wrong logically here. First, you write some text to the MemoryStream and then you write an empty array to the same stream. I assume you are trying to copy the contents of the stream into the bytesInStream array. You can create this array by calling memoryStream.ToArray().

    Alternatively, you can avoid the array copying by writing the stream directly to the response output stream using MemoryStream.CopyTo. Replace your BinaryWrite call with this:

     memoryStream.Position = 0;
     memoryStream.CopyTo(Response.OutputStream);
    

    Note: explicitly position the stream at the start since CopyTo will copy from the current position.

提交回复
热议问题