[英]C# Error - System.FormatException
有人在幫助我解決另一個問題,並給了我一個很好的代碼示例。 我嘗試進行一些調整以寫入文件而不是控制台,但出現以下錯誤:
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格式的有效日期。 知道我在做什么錯嗎?
確保文本沒有空格,請密切注意肉眼看不見的任何回車和換行字符。 字符串方法Trim是刪除此類空白的好函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.