CsvHelper没有将任何内容写入内存流 [英] CsvHelper not writing anything to memory stream

查看:54
本文介绍了CsvHelper没有将任何内容写入内存流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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

使用一个对象列表来调用它-最终是从数据库中调用的,但是由于某些事情不起作用,我只是填充一个静态集合.传递的对象如下:

Which is being called with a list of objects - eventually from a database, but since something is not working I'm just populating a static collection. The objects being passed are as follows:

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

我想做的是将一个集合写入一个csv,以便在MVC应用程序中下载.但是,每次我尝试写入该方法时,MemoryStream都会返回零长度,并且没有任何内容传递给它.我以前使用过此功能,但由于某种原因它无法正常工作-我有些困惑.谁能指出我在这里做错了什么?

What I'm trying to do is write a collection to a csv for download in an MVC application. Every time I try to write to the method though, the MemoryStream is coming back with zero length and nothing being passed to it. I've used this before, but for some reason it's just not working - I'm somewhat confused. Can anyone point out to me what I've done wrong here?

欢呼

推荐答案

放入 csvWriter.Flush(); ,然后再返回以刷新编写器/流.

Put csvWriter.Flush(); before you return to flush the writer/stream.

每位杰克的回应.应该是刷新的流,而不是csvWriter. streamWriter.Flush(); .保留原始解决方案,但添加此更正.

Per Jack's response. It should be the stream that gets flushed, not the csvWriter. streamWriter.Flush();. Leaving original solution, but adding this correction.

我的首选答案是: https://stackoverflow.com/a/22997765/1795053 使用语句为您完成繁重的工作

EDIT 2: My preferred answer is: https://stackoverflow.com/a/22997765/1795053 Let the using statements do the heavy lifting for you

这篇关于CsvHelper没有将任何内容写入内存流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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