简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM