有人在帮我解决另一个问题并给了我一个效果很好的代码示例。我尝试稍微调整一下来写一个文件而不是控制台,我收到了以下错误:
System.FormatException:字符串未被识别为有效的DateTime
代码如下:
// 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);
}
}
}
我已验证dateString
确实包含yyyyMMdd格式的有效日期。知道我做错了吗?