创建文本文件并下载

时间:2010-12-31 13:44:36

标签: c# asp.net file download

我正在尝试写入内存中的文本文件,然后下载该文件而不将文件保存到硬盘。我正在使用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();

7 个答案:

答案 0 :(得分:17)

这解决了我:

        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();     

答案 1 :(得分:14)

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

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

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

答案 2 :(得分:5)

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

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

另请记住设置ContentType

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

答案 3 :(得分:2)

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

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

我了解到,否则,下载有时无法成功完成。

This Google Groups posting还指出,Response.End会引发ThreadAbortException,您可以使用CompleteRequest方法避免使用{{1}}。

答案 4 :(得分:0)

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

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

示例(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");
    }

答案 5 :(得分:0)

扩展@Vinicious回答。

我的数据可能包含逗号。常见的解决方案是通过将其括在引号中来逃避该数据,同时确保也可以转义也可能是数据一部分的引号。

我遇到了一个问题并且在写入CSV时发出警告,如果你在逗号上留下空格,excel将不会喜欢你。 discovered solution to my problem from superuser answer

 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)));

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

df <- data.frame(name = rep("a",5), val1 = c(1,1,2,2,2), val2 = c(10,11,12,13,14))

> df
  name val1 val2
1    a    1   10
2    a    1   11
3    a    2   12
4    a    2   13
5    a    2   14

答案 6 :(得分:-1)

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