-1

I am using CsvHelper library to read the data from a CSV file looks like

this

My code:

public class CsvTransaction
{

    [Name("Account")]
    public string Account { get; set; }
    [Name("Amount")]
    public int Amount { get; set; }
    [Name("Date")]
    public DateTime Date { get; set; }
    [Name("Note")]
    public string Note { get; set; }
}

public void call()
            {
                using (var StreamReader = new StreamReader(@"C:\Users\santo\Downloads\industry.csv"))
                {
                    using (var csvReader = new CsvReader(StreamReader, CultureInfo.InvariantCulture))
                    {
                        var records = csvReader.GetRecords<CsvTransaction>().ToList();
                        Console.WriteLine(records.Count);
                        foreach(var item in records)
                         {
                            Console.WriteLine(item.Amount.GetType());
                            Console.WriteLine(item.Note.GetType());
                        

                        CsvAddTransaction(item.Account, item.Amount, item.Date, item.Note);
                    }
                    }
                }
            }

when I call this call(), it is saying String '22-05-1998' was not recognized as a valid DateTime. all the other are giving exact datatypes I needed, but there is a problem with item.Date

Can anyone help me with this?

monaca
  • 11
  • Do you get the same thing if that string is input manually? If so I suspect that there may be a "surprise" character in your CSV file, something like an em-dash – Jon P Mar 24 '22 at 05:16
  • @jon P there is no surprise character in CSV file, you can see the data in the image that I have attached – monaca Mar 24 '22 at 05:38
  • Not familiar with CSVHelper, but some internet pages suggest that you can use `TypeConverterOption` or `FormatAttribute`. [Page I found is in japanese](https://tomisenblog.com/csvhelper-datetime-mapping/), but there are codes and I think you can found similar topics at SO too. Seems like you have to tell it the format is `DD-MM-YYYY`. – Xiang Wei Huang Mar 24 '22 at 05:48
  • 1
    I assume that "InvariantCulture" also specifies date handling - which would be the US MM/dd/yyyy format So try a culture that uses dd-MM-yyyy. Note that it would also affect handling of decimals (`.` versus `,`) – Hans Kesting Mar 24 '22 at 08:14
  • Does this answer your question? [CsvHelper changing how dates and times are output](https://stackoverflow.com/questions/39564585/csvhelper-changing-how-dates-and-times-are-output) – David Specht Mar 24 '22 at 14:56

1 Answers1

1

You have to define DateTime format, you are getting this error because parsing mechanism might be expecting something like "MM-dd-yyyy" and instead of that, it receives "dd-MM-yyyy".

Here's documentation which describes DateTime formatting in detail. And here is url to potential solution to your problem.

eldpcn
  • 11
  • 4