Jay Donovan
Jay Donovan

Reputation: 25

C# Error - System.FormatException

Someone was helping me with another question and gave me a code example that worked great. I tried tweaking it a bit to write to a file instead of the console and I'm getting the following error:

System.FormatException: String was not recognized as a valid DateTime

The code is as follows:

// There is probably a more efficient way to do this...
string[] getFiles = Directory.GetFiles(@"C:\TestFiles", "*.x12");
string fn = getFiles[0];

string text = File.ReadAllText(fn);

var lines = text.Split('\n');

using (StreamWriter sw = new StreamWriter("outfile.txt"))
{
    foreach (var line in lines)
    {
        if (line.StartsWith("DTP*348"))
        {
            var elements = line.Split('*');
            var dateString = elements[3];

            var dateFormat = "yyyyMMdd";
            var date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture); // The error is thrown by this line

            if (date < new DateTime(2014, 06, 01))
            {
                date = new DateTime(2014, 06, 01);
                sw.WriteLine("DTP*" + elements[1] + "*" + elements[2] + "*" + "20140601");
            }
            else
            {
                sw.WriteLine(line);
            }
        }
        else
        {
            sw.WriteLine(line);
        }
    }
}

I have verified that dateString does contain a valid date in yyyyMMdd format. Any idea what I'm doing wrong?

Upvotes: 2

Views: 389

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31656

Make sure that the text to has no whitespace, pay close attention to any carriage return and line feed characters which are invisible to the naked eye. The string method Trim is a good function to remove such whitespace.

Upvotes: 3

Related Questions