将字符串转换为流 [英] convert string to stream

查看:144
本文介绍了将字符串转换为流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Controller.File方法返回一个较大的.csv文件作为操作结果,它要求我使用 byte [] 或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.

当使用 GetBytes 方法时,我得到了 OutOfMemoryException .

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

推荐答案

您尝试过吗?

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

如果您的数据确实那么大,这可能无济于事.如果生成的非常大csv文件,建议您重写 ToCsv()生成 stream 而不是 string.

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.

这篇关于将字符串转换为流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆