简体   繁体   中英

convert string to stream

I'm trying to return a large .csv file as an action result using the Controller.File method, and it requires that I use either a byte[] or a Stream.

When using GetBytes method, I'm getting an OutOfMemoryException .

Is there any way to do this without trying to put it all in memory at the same time?

Here's the return I'm using at the moment:

string csv = data.ToCsv();
return File(Encoding.UTF8.GetBytes(csv), "text/csv", "ClusterFMCacheExport.csv");

Have you tried this?

using(MemoryStream stream = new MemoryStream())
using(StreamWriter writer = new StreamWriter(stream))
{
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return File(stream, "text/csv", "ClusterFMCacheExport.csv");
}

If your data is really that big, this might not help. If your generating a very large csv files, I suggest you re-write the ToCsv() generate a stream rather than a string .

haven't used ASP.NET for some time, but shouldn't something like this work (assuming that file is on disk already):

FileStream fs = ... // stream over your csv file, however you get it
return File(fs, "application/csv", "file.csv");

Wouldn't:

Response.AddHeader("content-disposition", "attachment;filename=file.csv");
return Content(csv, "application/csv");

avoid the conversion? It might just kick it down the road though, only for the OOME to re-emerge elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM