Write a file “on-the-fly” to the client with C#

2020-03-02 01:56发布

I'm using C# and ASP.NET 2.5.

I want a simple way to generate a "file" on-the-fly (let's say a csv file for this example) and transmit it to the client without actually writing it to the server file system.

标签: c# asp.net
3条回答
来,给爷笑一个
3楼-- · 2020-03-02 02:46

After some searching and trial and error, I developed the following. It seems to fit the bill exactly. It should be very easily adaptable to PHP or any other server-side software since it mostly involves modifying headers.

protected void streamToResponse()
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=testfile.csv");
    Response.AddHeader("content-type", "text/csv");

    using(StreamWriter writer = new StreamWriter(Response.OutputStream))
    {
        writer.WriteLine("col1,col2,col3");
        writer.WriteLine("1,2,3");
    }
    Response.End();
}
查看更多
家丑人穷心不美
4楼-- · 2020-03-02 02:52

May I also suggest, that if you have something other than text, say, binary, you use the Response.WriteBinary() method

I've often created a JPG on the fly, wrote it to a MemoryStream using the Bitmap.Save() method, turned the MemoryStream into a byte[] array using .ToArray() and then Response.WriteBinary() that array.

查看更多
登录 后发表回答