我有以下方法:
我想做的是在MVC应用程序中将一组内容写入CSV进行下载。 但每次尝试写入方法时,MemoryStream都会返回零长度,并且没有传递任何内容。 我之前使用过这个方法,但由于某种原因它现在无法正常工作-我有点困惑。 有人可以指出我在这里做错了什么吗?
我有以下方法:
public byte[] WriteCsvWithHeaderToMemory<T>(IEnumerable<T> records) where T : class
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteRecords<T>(records);
return memoryStream.ToArray();
}
}
这个函数被调用的时候会传递一个对象列表 - 通常来自于数据库,但是由于某些问题,我只是暂时使用静态集合填充。被传递的对象如下:
using CsvHelper.Configuration;
namespace Application.Models.ViewModels
{
public class Model
{
[CsvField(Name = "Field 1", Ignore = false)]
public string Field1 { get; set; }
[CsvField(Name = "Statistic 1", Ignore = false)]
public int Stat1{ get; set; }
[CsvField(Name = "Statistic 2", Ignore = false)]
public int Stat2{ get; set; }
[CsvField(Name = "Statistic 3", Ignore = false)]
public int Stat3{ get; set; }
[CsvField(Name = "Statistic 4", Ignore = false)]
public int Stat4{ get; set; }
}
}
我想做的是在MVC应用程序中将一组内容写入CSV进行下载。 但每次尝试写入方法时,MemoryStream都会返回零长度,并且没有传递任何内容。 我之前使用过这个方法,但由于某种原因它现在无法正常工作-我有点困惑。 有人可以指出我在这里做错了什么吗?
csvWriter.Flush();
。 - Eli Gassert