CsvHelper没有将任何内容写入内存流

编程入门 行业动态 更新时间:2024-10-25 00:30:22
本文介绍了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.

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

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

更多推荐

CsvHelper没有将任何内容写入内存流

本文发布于:2023-08-01 04:30:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265230.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   内容   CsvHelper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!