【发布时间】:2015-07-08 20:49:22
【问题描述】:
有人帮我解决了另一个问题,并给了我一个效果很好的代码示例。我尝试稍微调整一下以写入文件而不是控制台,但出现以下错误:
System.FormatException:字符串未被识别为有效的日期时间
代码如下:
// 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 格式的有效日期。知道我做错了什么吗?
【问题讨论】:
-
我猜你可能没有修剪空格或其他字符?我刚刚使用一些示例值测试了您的格式字符串和语句,它对我来说效果很好。您可以粘贴
dateString值的“确切”值吗? -
抛出异常的时候为什么不用调试器来验证值呢?
-
我想通了。日期之后的文件中有一个尾随 \r。谢谢!
-
为什么不使用
try{...} catch (exception e){...}并查看异常消息和堆栈? -
我是新来的,问题解决后我该怎么办?我应该留下它还是应该删除它?
标签: c#