Create text file and download

前端 未结 7 1115
日久生厌
日久生厌 2020-12-14 01:08

I\'m trying to write to a text file in memory and then download that file without saving the file to the hard disk. I\'m using the StringWriter to write the con

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 01:36

    I had many issues with this. Finnaly found a solution that seems to work everytime.

    In most cases the user is going to click a button for the download. At this point it is best to redirect the page back to the same spot. add a parameter in the url that you can grab and read.

    example( www.somewhere.com/mypage.aspx?print=stuff)

        
    
    
        protected void Page_Load(object sender, EventArgs e) {
            if (Request["print"] == "stuff") { Print("my test content"); }
        }
    
        /* or pass byte[] content*/
        private void Print(string content ){ 
            Response.ContentType = "text/plain";
            Response.AddHeader("content-disposition", "attachment;filename=myFile.txt");
            // Response.BinaryWrite(content);
            Response.Write(content);
            Response.Flush(); 
            Response.End();
        }
    
        protected void btn_Click(object sender, EventArgs e) {
            // postbacks give you troubles if using async.
            // Will give an error when Response.End() is called.
            Response.Redirect(Request.Url + "?print=queue");
        }
    

提交回复
热议问题