c# - CSV Helper not writing to file -


i've been stuck trying csv helper write file. when run action downloads file proper name , else, never writes it.

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; 

}

the action:

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

i've tried using documentation csv helper , can't write. here's i've got that...

// copyright 2009-2015 josh close , contributors // file part of csvhelper , dual licensed under ms-pl , apache 2.0. // see license.txt details or visit http://www.opensource.org/licenses/ms-pl.html ms-pl , http://opensource.org/licenses/apache-2.0 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 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 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 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 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 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 records 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 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 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);             }         }     } } 

can point me might missing or doing wrong?

if have datatable can convert comma separated value list of strings this...

/// <summary> /// creates comma separated value string datatable. /// </summary> public static string tocsv(datatable table)  {     stringbuilder csv = new stringbuilder();     for(int = 0; < table.columns.count ;i++) // process column headers     {         if (i > 0)             csv.append(",");         csv.append(_formattocsvfield(table.columns[i].columnname));     }     if (table.columns.count > 0)         csv.append("\r\n");     (int = 0; < table.rows.count; i++) // process row data     {         (int j = 0; j < table.columns.count; j++) // process each field in 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("\"", "\"\"") + "\""; } 

or if didn't have datatable; take take created comma separated value (csv) list of string "row1 column 1, row1 column2, row1 column3, \r\n, row2, colum1... etc..."

and save csv file, this...

            //your csv string         string whattowrite =  "row1 column 1, row1 column2, row1 column3, \r\n";          //convert csv string byte[]         byte[] putwhattowriteintobytes = encoding.getencoding("iso-8859-1").getbytes(whattowrite);          //write byte[] csv readable 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(); 

its hard follow code. trying write csv...get that; check if good. write file. determine if writing empty string, or if writing losing string


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -