1

I am using the following code and getting an exception ,

 Exception thrown: 'CsvHelper.WriterException' in CsvHelper.dll on this line executed:

csv.WriteRecord(item);

This is the more of the code:

using (var memoryStream = new MemoryStream())
{
    using (var writer = new StreamWriter(memoryStream))
    {
        using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            foreach (var item in csvData)
            {
                csv.WriteRecord(item); // Exception thrown here
            }
        }
    }

    var arr = memoryStream.ToArray();
    //js.SaveAs("people.csv", arr);  what type object is js? copied from the stackoverflow answer linked here
}

This is the csvData code:

IEnumerable<DateLowHigh> csvData = stocks.candles
    .Select(c => new DateLowHigh
    {
        Time = c.datetime,
        Close = c.close,
        Low = c.low,
        High = c.high
    })
    .ToList();

I do get the csvData.

This stackoverflow answer helped me get started.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
Jam66125
  • 163
  • 2
  • 8

2 Answers2

0

I don't know why you need to use CsvHelper when you can easily do the same with the IO library.

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            Stocks stocks = new Stocks();

            IEnumerable<DateLowHigh> csvData = stocks.candles.Select(c => new DateLowHigh
            {
                Time = c.datetime,
                Close = c.close,
                Low = c.low,
                High = c.high
            }).ToList();

            MemoryStream memoryStream = new MemoryStream();
            using (var writer = new StreamWriter(memoryStream))
            {
                string[] headers = {"Time", "Close", "Low", "High"};
                writer.WriteLine(string.Join(",", headers));
                foreach (var item in csvData)
                {
                    writer.WriteLine(string.Join(",", new string[] { item.Time.ToString(), item.Close, item.Low.ToString(), item.High.ToString() }));
                }  
            }
            memoryStream.Position = 0;
        }
    }
    public class Stocks
    {
        public List<Candle> candles { get; set; }
    }
    public class Candle
    {
        public DateTime datetime { get; set; }
        public string close { get; set; }        
        public int low { get; set; }
        public int high { get; set; }
    }
    public class DateLowHigh
    {
        public DateTime Time { get; set; }
        public string Close { get; set; }
        public int Low { get; set; }
        public int High { get; set; }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • 1
    You'd use a CSV library so you don't have to rewrite this same boiler plate code every time you need to write something different to a file. Also because it can handle things like having a comma in the data. – juharr Feb 16 '20 at 16:13
  • The code is one line. I can see using a library when it is lots of lines of common code. But ONE line???? – jdweng Feb 16 '20 at 17:10
  • @jdweng, your code is four lines. Two for the header and two for the rest of the lines. Currently your code will not output correct CSV if the property `Close` has a comma or line break in it. Also imagine your code if `DateLowHigh` had 200 properties to write out. If `DateLowHigh` changes or adds properties, you will have to go back to your code to change it. With `CsvHelper` it could be simply `csv.WriteRecords(csvData);` – David Specht Feb 18 '20 at 18:43
  • But how can you format the output easily? My code you can easily format the date, and not have to use a useless library that give phantom error messages. – jdweng Feb 18 '20 at 22:55
  • @jdweng I agree that a CSV library seems to be a bit of overkill for a rather simple looking problem. However, I have spent countless hours of frustration trying to find and correct CSV files where the person creating them didn't enclose fields with commas or line endings in double quotes or escape double quotes within a field. CsvHelper has ways to easily format data and there was more to the error message than the original poster included. – David Specht Feb 19 '20 at 13:29
0

To answer your question as to what type of object js is in js.SaveAs("people.csv", arr); it is likely Microsoft.JSInterop.IJSRuntime as seen in this Blazer HowTo. The StackOverflow question you referenced was likely using it to get access to JavaScript they could use in C# code. If you just want to save a CSV file using CsvHelper, it could be as simple as:

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{    
    csv.WriteRecords(csvData);
}

If you are still getting errors, you would need to post the full exception with StackTrace in order to help further.

David Specht
  • 7,784
  • 1
  • 22
  • 30