【问题标题】:Create text file and download创建文本文件并下载
【发布时间】:2010-12-31 13:44:36
【问题描述】:

我正在尝试写入内存中的文本文件,然后下载该文件而不将文件保存到硬盘。我正在使用StringWriter 来编写内容:

StringWriter oStringWriter = new StringWriter();
oStringWriter.Write("This is the content");

然后我该如何下载这个文件?

编辑: 答案的组合给了我我的解决方案。这里是:

StringWriter oStringWriter = new StringWriter();
oStringWriter.WriteLine("Line 1");
Response.ContentType = "text/plain";

Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("members-{0}.csv",string.Format("{0:ddMMyyyy}",DateTime.Today)));
Response.Clear();

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
    writer.Write(oStringWriter.ToString());
}
Response.End();

【问题讨论】:

    标签: c# asp.net file download


    【解决方案1】:

    这为我解决了:

            MemoryStream ms = new MemoryStream();
            TextWriter tw = new StreamWriter(ms);
            tw.WriteLine("Line 1");
            tw.WriteLine("Line 2");
            tw.WriteLine("Line 3");
            tw.Flush();
            byte[] bytes = ms.ToArray();
            ms.Close();
    
            Response.Clear();
            Response.ContentType = "application/force-download";
            Response.AddHeader("content-disposition", "attachment;    filename=file.txt");
            Response.BinaryWrite(bytes);
            Response.End();     
    

    【讨论】:

      【解决方案2】:

      你可以直接将数据写入响应流,而不是将数据存储在内存中,然后将其发送到响应流中:

      using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
        writer.Write("This is the content");
      }
      

      该示例使用 UTF-8 编码,如果您使用其他编码,则应更改它。

      【讨论】:

      • 嗨,Guffa - 我如何让响应流下载呢?
      • @higgsy:您在标题中添加内容处置和内容类型的说明,以便浏览器知道它是什么。 Klaus Byskow Hoffman 在他的回答中有一些示例,但您不必使用 HTTP 处理程序来返回响应,它也适用于常规页面。您还应该在内容类型中指定编码,例如text/plain; charset=utf-8
      【解决方案3】:

      基本上你通过实现IHttpHandler 接口来创建一个HttpHandler。在ProcessRequest 方法中,您基本上只需将文本写入context.Response。您还需要添加一个Content-Disposition http 标头:

      context.Response.AddHeader("Content-Disposition", "attachment; filename=YourFileName.txt");
      

      还记得设置ContentType:

      context.Response.ContentType = "text/plain";
      

      【讨论】:

        【解决方案4】:

        只是对其他答案的一个小补充。在下载的最后我执行:

        context.Response.Flush();
        context.ApplicationInstance.CompleteRequest();
        

        我了解到,否则有时下载不会成功完成。

        This Google Groups posting 还注意到Response.End 会抛出一个ThreadAbortException,您可以通过使用CompleteRequest 方法来避免这种情况。

        【讨论】:

        • 实际上,当我使用您添加的行时,生成的文件包含我在流中编写的文本以及渲染的 html 代码,所以我不得不返回代码并只输入“响应.End" 行,它工作得很好!
        • 通常,我只通过单独的 ASHX 处理程序提供下载,而不是在 ASPX 页面中。
        【解决方案5】:

        我对此有很多问题。 Finnaly 找到了一个似乎每次都能奏效的解决方案。

        在大多数情况下,用户会单击一个按钮进行下载。此时最好将页面重定向回同一位置。在 url 中添加一个可以抓取和阅读的参数。

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

            <asp:Button ID="btn" runat="server" Text="print something" OnClick="btn_Click" />
        
        
            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");
            }
        

        【讨论】:

          【解决方案6】:

          @Vinicious 答案的扩展。

          我有可能包含逗号的数据。常见的解决方案是通过用引号括起来来转义该数据,同时确保也转义可能也是数据一部分的引号。

          我在编写 CSV 时遇到了一个问题和一个警告,如果你在逗号后面加上空格,excel 不会喜欢你。 discovered solution to my problem from superuser answer

          protected void btnDownload_Click(object sender, EventArgs e)
          {
              MemoryStream ms = new MemoryStream();
              TextWriter tw = new StreamWriter(ms, System.Text.Encoding.UTF8);
              var structures = KAWSLib.BusinessLayer.Structure.GetStructuresInService();
              // *** comma delimited
              tw.Write("Latitude, Longitude, CountySerial, StructureType, Orientation, District, RoutePre, RouteNo, LocationDesc");
              foreach (var s in structures)
              {
                  tw.Write(Environment.NewLine + string.Format("{0:#.000000},{1:#.000000},{2},{3},{4},{5},{6},{7},{8}", s.LATITUDE, s.LONGITUDE, s.CO_SER, EscapeIfNeeded(s.SuperTypeLookup.SHORTDESC), EscapeIfNeeded(s.OrientationLookup.SHORTDESC), s.DISTRICT, s.ROUTE_PREFIX, s.RouteValue, EscapeIfNeeded(s.LOC_DESC)));
              }
              tw.Flush();
              byte[] bytes = ms.ToArray();
              ms.Close();
          
              Response.Clear();
              Response.ContentType = "application/force-download";
              Response.AddHeader("content-disposition", "attachment;    filename=" + string.Format("kaws-structures-{0:yyyy.MM.dd}.csv", DateTime.Today));
              Response.BinaryWrite(bytes);
              Response.End();
          }
          
          string EscapeIfNeeded(string s)
          {
              if (s.Contains(","))
              {
                  return "\"" + s.Replace("\"", "\"\"") + "\"";
              }
              else
              {
                  return s;
              }
          }
          

          下面会导致excel出现问题。在 excel 中,第一个引号将成为数据的一部分,因此在嵌入的逗号处分开。空间不好。

           tw.Write(Environment.NewLine + string.Format("{0:#.000000}, {1:#.000000}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", s.LATITUDE, s.LONGITUDE, s.CO_SER, EscapeIfNeeded(s.SuperTypeLookup.SHORTDESC), EscapeIfNeeded(s.OrientationLookup.SHORTDESC), s.DISTRICT, s.ROUTE_PREFIX, s.RouteValue, EscapeIfNeeded(s.LOC_DESC)));
          

          【讨论】:

            【解决方案7】:

            这个很简单,答案可以看这篇微软知识库文章:How to write binary files to the browser using ASP.NET and C#

            【讨论】:

            • 这并不能真正回答问题... higgsy 指定不应将文件写入硬盘。
            • 嗨,确切地说,该文件不应该写入硬盘。
            猜你喜欢
            • 1970-01-01
            • 2022-11-04
            • 1970-01-01
            • 2011-01-16
            • 2022-01-07
            • 2013-12-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多