How to download memorystream to a file?

前端 未结 4 2004
半阙折子戏
半阙折子戏 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:24

    At the point in your code where you copy the data to an array, the TextWriter might not have flushed the data. This will happen when you Flush() or when you Close() it.

    See if this works:

    MemoryStream memoryStream = new MemoryStream();
    TextWriter textWriter = new StreamWriter(memoryStream);
    textWriter.WriteLine("Something");   
    textWriter.Flush(); // added this line
    byte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array
    memoryStream.Close(); 
    
    Response.Clear();
    Response.ContentType = "application/force-download";
    Response.AddHeader("content-disposition", "attachment;    filename=name_you_file.xls");
    Response.BinaryWrite(bytesInStream);
    Response.End();
    

提交回复
热议问题