2013-05-21 101 views
1

我正在编写一个集成测试,因此我正在读取一个CSV文件作为DataTable,然后尝试解析每行中的元素。然而,当我得到一个日期的字符串表示,并把它传递到DateTime.ParseExact我得到的错误:“字符串未被识别为有效的DateTimeParseExact无法识别从DataTable中提取的字符串

当我使用注释掉的行代码我在这里提供,并明确定义日期为一个字符串,然后ParseExact工作得很好。当我调试集成测试时,startDateString具有正确的日期值。 Debug capture of the value from the DataTable当它传入ParseExact由于某些原因它会引发错误。

我试图使用明确的文化,例如。 “en-GB”和DateStyles.None,没有太大的成功。有没有人有任何想法,至于为什么从DataRow得到的字符串输入不被DateTime.ParseExact构造函数接受?

谢谢。

... 
var dataTable= file.ReadFile("file.csv", 2); 
      for (int i = 0; i < dataTable.Rows.Count/2; i = i + 2) 
      { 
       var startDate = new DateTime(); 
       var maturity= new DateTime(); 
       try 
       { 
        var startDateString = dataTable.Rows[i]["item9"].ToString(); 
//     var startDateString = "24/01/2008"; 
        var formats = new[] { "dd/M/yyyy", "dd/MM/yyyy" }; 
        startDate = DateTime.ParseExact(startDateString, formats, CultureInfo.InvariantCulture, 
             DateTimeStyles.AssumeLocal); 
        endDate = DateTime.ParseExact(dataTable.Rows[i]["item10"].ToString(), formats, CultureInfo.InvariantCulture, 
             DateTimeStyles.AssumeLocal); 
       } 
       catch (Exception e) 
       { 
        throw new FormatException(String.Format("There was an error with the format of one of the dates in the file")); 
       } 
... 
+0

是否有可能从“item9”列中拉出的值不是日期?你确认从数据表中分配给startDateString的值是你期望的吗? – Jeff

+0

检查dataTable.Rows [i] [“item10”]。ToString()'并在此处发布 – oleksii

+0

以下是从DataRow返回的值的调试捕获。有任何想法吗? – cmdel

回答

1

您的startDateString在其中有尾随空格。

+0

好的电话!我昨天工作得太迟了,看起来,在我面前看不清楚!感谢大家换一双眼睛。 – cmdel