How to read from .csv file with TextFieldParser using a specified date format?

1.2k views Asked by At

EDIT: This question was based off me misunderstanding Excel's behavior. I kept thinking the M/DD/YYYY format was in the input file but that was only Excel's reformatting of it, the TextFieldParser did indeed keep the original format YYYY-MM-DD. Thanks everyone for leading me to this conclusion.

I am reading from a .csv file for a console app using the TextFieldParser class in C# as follows:

using (TextFieldParser parser = new TextFieldParser(@"C:\myfilepath"))
{
    parser.TextFieldType = FieldType.Delimited; //set up parser
    parser.SetDelimiters(",", "|");

    string[] header = parser.ReadFields(); //process header
}

The format of dates in the input file is M/DD/YYYY. However, I need the format to be something else, say MM/DD/YYYY.

When the TextFieldParser reads date fields, it changes them to the format of YYYY-MM-DD, which I see in my output, so I know it is somehow recognizing fields that look like dates and converting them to a specific format. My problem boils down to simply changing this format. Hopefully there is some way to do this...

I know I could simply edit the strings of the dates after the parser has read them, but this seems sloppy to me.

Thanks.

1

There are 1 answers

1
yob On

Per MSDN TextFieldParser.ReadFields, TextFieldParser.ReadFields() - Reads all fields on the current line, returns them as an array of strings

Tried with following line in csv file:

     1,2019-10-04,04/10/2019,test

This works:

    using (TextFieldParser parser = new TextFieldParser(@"<path to testcsv.csv>"))
                {
                    parser.TextFieldType = FieldType.Delimited; 
                    parser.SetDelimiters(",", "|");

                    string[] current = parser.ReadFields();
                    string[] formats = new string[] { "yyyy-MM-dd", "dd/MM/yyyy", "MM/dd/yyyy" };
                    foreach (string f in current)
                    {
                        DateTime dv ;
                        if (DateTime.TryParseExact(f, formats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dv))
                        {
                            Console.WriteLine($"found date - { dv.ToLongDateString()}");
                        }
                        else 
                        {
                            Console.WriteLine($"found something  - {f}");
                        }
                    }
                }