foreach (var file in Directory.GetFiles(@"C:\Users\Andrew\Desktop\Timesheets\2011", "*.xlsx", SearchOption.AllDirectories)){
Paycheck p = new Paycheck(DateTime.ParseExact(file.Substring(file.LastIndexOf("_" + 1), 6), "dd/mm/yy", null), file);
_Paychecks.Add(p);
}
我正在尝试从我的程序将扫描的文件名中获取 DateTime。 DateTime 的格式为 dd/mm/yy。每次我到达这行代码时:
Paycheck p = new Paycheck(DateTime.ParseExact(file.Substring(file.LastIndexOf("_"+ 1), 6), "dd/mm/yy", null), 文件);
程序没有做任何事情就中断了应用程序。它不会给我一条错误消息和任何关于正在发生的事情的信息。我确定我以某种令人困惑的方式写了这篇文章,所以让我知道您需要澄清什么。
这是一个文件名示例,以防万一;
每周时间和费用表_AT_073111
请您参考如下方法:
您需要使用大写的MM来表示Month,而不是小写的mm
从你的示例日期字符串 07312011 看起来像
前两位数字 - 07 => 月份
接下来的两位数 - 31 => Date
接下来的四位数字 - 2011 => Year
因此你的格式应该是MMddyyyy
编辑:您需要在关闭 LastIndexOf() 函数后加 1
试试这个:
Paycheck p = new Paycheck(DateTime.ParseExact(file.Substring(
file.LastIndexOf("_") + 1, 6), "MMddyyyy", null), file);
