CSV助手不写入文件

我一直试图让CSV助手写入文件。 当我运行DownloadRegistrantsCsv它会以正确的名称和其他所有内容下载文件,但是它永远不会写入任何内容。

 public async Task<Stream> GetDownloadStreamAsync(int id) { var memoryStream = new MemoryStream(); var streamWriter = new StreamWriter(memoryStream); var streamReader = new StreamReader(memoryStream); var csvHelper = new CsvHelper.CsvWriter(streamWriter); csvHelper.WriteRecord(new EventRegistrant { FirstName = "Max" }); await memoryStream.FlushAsync(); memoryStream.Position = 0; return memoryStream; } public async Task<ActionResult> DownloadRegistrantsCsv(int id) { var @event = await _service.GetAsync(id, true); if (@event == null) return HttpNotFound(); var stream = await _service.GetDownloadStreamAsync(id); return File(stream, "application/txt", "test" + ".csv"); } 

我也尝试过使用CSV Helper的文档,我甚至无法写出来。 这是我得到的…

 // Copyright 2009-2015 Josh Close and Contributors // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. // http://csvhelper.com using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Web.Script.Serialization; using CsvHelper.Configuration; using CsvHelper.TypeConversion; namespace CsvHelper.Example { class Program { private const string columnSeparator = ":"; static void Main(string[] args) { //ReadRawFieldsByIndex(); //ReadRawFieldsByName(); //ReadFieldsByIndex(); //ReadRecordsNoAttributes(); //ReadRecordsWithAttributes(); //ReadAllRecords(); //WriteRawFields(); //WriteFields(); WriteRecordsNoAttributes(); //WriteRecordsWithAttributes(); WriteAllRecords(); Console.ReadKey(); } public static void ReadRawFieldsByIndex() { Console.WriteLine("Raw fields by index:"); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true)))) { while (reader.Read()) { Console.Write(reader.GetField(0) + columnSeparator); Console.Write(reader.GetField(1) + columnSeparator); Console.Write(reader.GetField(2) + columnSeparator); Console.WriteLine(reader.GetField(3)); } } Console.WriteLine(); } public static void ReadRawFieldsByName() { Console.WriteLine("Raw fields by name:"); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true)))) { while (reader.Read()) { Console.Write(reader.GetField("String Column") + columnSeparator); Console.Write(reader.GetField("Int Column") + columnSeparator); Console.Write(reader.GetField("Guid Column") + columnSeparator); Console.Write(reader.GetField("Does Not Exist Column") + columnSeparator); Console.WriteLine(reader.GetField("Custom Type Column")); } } Console.WriteLine(); } public static void ReadFieldsByIndex() { Console.WriteLine("Fields by index:"); var customTypeTypeConverter = new CustomTypeTypeConverter(); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true)))) { while (reader.Read()) { Console.Write(reader.GetField<string>(0) + columnSeparator); Console.Write(reader.GetField<int>("Int Column") + columnSeparator); Console.Write(reader.GetField<Guid>(2) + columnSeparator); Console.WriteLine(reader.GetField<CustomType>(3, customTypeTypeConverter)); } } Console.WriteLine(); } public static void ReadRecordsNoAttributes() { Console.WriteLine("Records no attributes:"); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, false)))) { while (reader.Read()) { Console.WriteLine(reader.GetRecord<CustomObject>()); } } Console.WriteLine(); } public static void ReadRecordsWithAttributes() { Console.WriteLine("Records with attributes:"); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, true)))) { reader.Configuration.RegisterClassMap<CustomObjectWithMappingMap>(); while (reader.Read()) { Console.WriteLine(reader.GetRecord<CustomObjectWithMapping>()); } } Console.WriteLine(); } public static void ReadAllRecords() { Console.WriteLine("All records:"); using (var reader = new CsvReader(new StreamReader(GetDataStream(true, false)))) { var records = reader.GetRecords<CustomObject>(); foreach (var record in records) { Console.WriteLine(record); } } Console.WriteLine(); } public static void WriteRawFields() { Console.WriteLine("Write raw fields"); using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var streamReader = new StreamReader(memoryStream)) using (var writer = new CsvWriter(streamWriter)) { writer.WriteField("String Column"); writer.WriteField("Int Column"); writer.WriteField("Guid Column"); writer.WriteField("Custom Type Column"); writer.NextRecord(); writer.WriteField("one"); writer.WriteField((1).ToString()); writer.WriteField(Guid.NewGuid().ToString()); writer.WriteField((new CustomType { First = 1, Second = 2, Third = 3 }).ToString()); writer.NextRecord(); memoryStream.Position = 0; Console.WriteLine(streamReader.ReadToEnd()); } Console.WriteLine(); } public static void WriteFields() { Console.WriteLine("Write fields"); using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var streamReader = new StreamReader(memoryStream)) using (var writer = new CsvWriter(streamWriter)) { writer.WriteField("String Column"); writer.WriteField("Int Column"); writer.WriteField("Guid Column"); writer.WriteField("Custom Type Column"); writer.NextRecord(); writer.WriteField("one"); writer.WriteField(1); writer.WriteField(Guid.NewGuid()); writer.WriteField(new CustomType { First = 1, Second = 2, Third = 3 }); writer.NextRecord(); memoryStream.Position = 0; Console.WriteLine(streamReader.ReadToEnd()); } Console.WriteLine(); } public static void WriteRecordsNoAttributes() { Console.WriteLine("Write records no attributes:"); var records = new List<CustomObject> { new CustomObject { CustomTypeColumn = new CustomType { First = 1, Second = 2, Third = 3, }, GuidColumn = Guid.NewGuid(), IntColumn = 1, StringColumn = "one", }, new CustomObject { CustomTypeColumn = new CustomType { First = 4, Second = 5, Third = 6, }, GuidColumn = Guid.NewGuid(), IntColumn = 2, StringColumn = "two", }, }; using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var streamReader = new StreamReader(memoryStream)) using (var writer = new CsvWriter(streamWriter)) { foreach (var record in records) { writer.WriteRecord(record); } memoryStream.Position = 0; Console.WriteLine(streamReader.ReadToEnd()); } Console.WriteLine(); } public static void WriteRecordsWithAttributes() { Console.WriteLine("Write records with attributes:"); var records = new List<CustomObjectWithMapping> { new CustomObjectWithMapping { CustomTypeColumn = new CustomType { First = 1, Second = 2, Third = 3, }, GuidColumn = Guid.NewGuid(), IntColumn = 1, StringColumn = "one", }, new CustomObjectWithMapping { CustomTypeColumn = new CustomType { First = 4, Second = 5, Third = 6, }, GuidColumn = Guid.NewGuid(), IntColumn = 2, StringColumn = "two", }, }; using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var streamReader = new StreamReader(memoryStream)) using (var writer = new CsvWriter(streamWriter)) { foreach (var record in records) { writer.WriteRecord(record); } memoryStream.Position = 0; Console.WriteLine(streamReader.ReadToEnd()); } Console.WriteLine(); } public static void WriteAllRecords() { Console.WriteLine("Write all records with attributes:"); var records = new List<CustomObjectWithMapping> { new CustomObjectWithMapping { CustomTypeColumn = new CustomType { First = 1, Second = 2, Third = 3, }, GuidColumn = Guid.NewGuid(), IntColumn = 1, StringColumn = "one", }, new CustomObjectWithMapping { CustomTypeColumn = new CustomType { First = 4, Second = 5, Third = 6, }, GuidColumn = Guid.NewGuid(), IntColumn = 2, StringColumn = "two", }, }; using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var streamReader = new StreamReader(memoryStream)) using (var writer = new CsvWriter(streamWriter)) { writer.Configuration.RegisterClassMap<CustomObjectWithMappingMap>(); writer.WriteRecords(records as IEnumerable); memoryStream.Position = 0; Console.WriteLine(streamReader.ReadToEnd()); } Console.WriteLine(); } public static MemoryStream GetDataStream(bool hasHeader, bool hasSpacesInHeaderNames) { var stream = new MemoryStream(); var writer = new StreamWriter(stream); if (hasHeader) { var header = hasSpacesInHeaderNames ? "String Column,Int Column,Guid Column,Custom Type Column" : "StringColumn,IntColumn,GuidColumn,CustomTypeColumn"; writer.WriteLine(header); } writer.WriteLine("one,1,{0},1|2|3", Guid.NewGuid()); writer.WriteLine("two,2,{0},4|5|6", Guid.NewGuid()); writer.WriteLine("\"this, has a comma\",2,{0},7|8|9", Guid.NewGuid()); writer.WriteLine("\"this has \"\"'s\",4,{0},10|11|12", Guid.NewGuid()); writer.Flush(); stream.Position = 0; return stream; } public class CustomType { public int First { get; set; } public int Second { get; set; } public int Third { get; set; } public override string ToString() { var serializer = new JavaScriptSerializer(); return serializer.Serialize(this); } } public class CustomTypeTypeConverter : ITypeConverter { public string ConvertToString(TypeConverterOptions options, object value) { var obj = (CustomType)value; return string.Format("{0}|{1}|{2}", obj.First, obj.Second, obj.Third); } public object ConvertFromString(TypeConverterOptions options, string text) { var values = ((string)text).Split('|'); var obj = new CustomType { First = int.Parse(values[0]), Second = int.Parse(values[1]), Third = int.Parse(values[2]), }; return obj; } public bool CanConvertFrom(Type type) { throw new NotImplementedException(); } public bool CanConvertTo(Type type) { throw new NotImplementedException(); } } public class CustomObject { public CustomType CustomTypeColumn { get; set; } public Guid GuidColumn { get; set; } public int IntColumn { get; set; } public string StringColumn { get; set; } public override string ToString() { var serializer = new JavaScriptSerializer(); return serializer.Serialize(this); } } public class CustomObjectWithMapping { public CustomType CustomTypeColumn { get; set; } public Guid GuidColumn { get; set; } public int IntColumn { get; set; } public string StringColumn { get; set; } public string IgnoredColumn { get; set; } //public override string ToString() //{ // var serializer = new JavaScriptSerializer(); // return serializer.Serialize(this); //} } public sealed class CustomObjectWithMappingMap : CsvClassMap<CustomObjectWithMapping> { public CustomObjectWithMappingMap() { Map(m => m.CustomTypeColumn).Name("Custom Type Column").Index(3).TypeConverter<CustomTypeTypeConverter>(); Map(m => m.GuidColumn).Name("Guid Column").Index(2); Map(m => m.IntColumn).Name("Int Column").Index(1); Map(m => m.StringColumn).Name("String Column").Index(0); } } } } 

任何人都可以指出我可能会失踪或做错吗?

如果你有一个DataTable,你可以将它转换成一个逗号分隔值的string列表像这样…

 /// <summary> /// Creates a comma separated value string from a datatable. /// </summary> public static string ToCSV(DataTable table) { StringBuilder csv = new StringBuilder(); for(int i = 0; i < table.Columns.Count ;i++) // process the column headers { if (i > 0) csv.Append(","); csv.Append(_FormatToCSVField(table.Columns[i].ColumnName)); } if (table.Columns.Count > 0) csv.Append("\r\n"); for (int i = 0; i < table.Rows.Count; i++) // process the row data { for (int j = 0; j < table.Columns.Count; j++) // process each field in the data row. { if (j > 0) csv.Append(","); csv.Append(_FormatToCSVField(table.Rows[i][j].ToString())); } csv.Append("\r\n"); } return csv.ToString(); } private static string _FormatToCSVField(string unformattedField) { return "\"" + unformattedField.Replace("\"", "\"\"") + "\""; } 

或者如果您没有DataTable, 采取您创build的逗号分隔值(CSV)列表string“row1列1,行1列2,行1列3,\ r \ n,行2,列1 …等…”

并保存到一个CSV文件,像这样…

  //Your CSV String string WhatToWrite = "row1 column 1, row1 column2, row1 column3, \r\n"; //Convert your CSV String to byte[] byte[] PutWhatToWriteIntoBytes = Encoding.GetEncoding("iso-8859-1").GetBytes(WhatToWrite); //Write the byte[] to CSV readable by excel string filename = "WhatYouWantToCallYourFile" + ".csv"; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", filename.ToString()); Response.Clear(); Response.BinaryWrite(PutWhatToWriteIntoBytes); Response.End(); 

它真的很难遵循所有的代码。 究竟是什么,你试图写入一个CSV …得到的; 检查它是否好。 然后写入文件。 确定是否正在写一个空string,或者如果正在写string丢失