【问题标题】:output a .txt file from a StreamWriter without writing to disk?从 StreamWriter 输出 .txt 文件而不写入磁盘?
【发布时间】:2009-02-17 11:45:46
【问题描述】:

是否有任何方法可以获取 StreamWriter 并将文件(在本例中为 .txt 文件)输出给用户,并且可以选择打开/保存而不将文件实际写入磁盘?不保存的话基本就没了。

我正在寻找与

相同的功能
HttpContext.Current.Response.TransmitFile(file);

但无需将任何内容保存到磁盘。谢谢!

【问题讨论】:

    标签: c# asp.net .net


    【解决方案1】:

    试试System.IO.MemoryStream

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
    sw.Write("hello");
    

    【讨论】:

      【解决方案2】:

      我最近做了一个 XML 文件,应该很容易适应

      protected void Page_Load(object sender, EventArgs e)
              {
                  Response.Clear();
                  Response.AppendHeader("content-disposition", "attachment; filename=myfile.xml");
                  Response.ContentType = "text/xml";
                  UTF8Encoding encoding = new UTF8Encoding();
                  Response.BinaryWrite(encoding.GetBytes("my string"));
                  Response.Flush();
                  Response.End();
              }
      

      【讨论】:

        【解决方案3】:

        或使用 Response.BinaryWrite(byte[]);

        Response.AppendHeader("Content-Disposition", @"Attachment; Filename=MyFile.txt");                                               
        Response.ContentType = "plain/text";    
        Response.BinaryWrite(textFileBytes);
        

        类似的东西应该可以。如果您在流中有文本文件,则可以轻松地从中获取 byte[]。

        编辑:见上文,但明显更改 ContentType。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-08-09
          • 2021-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多