我的目录中有文件,文件名如下:
Batch 1.10.18.xlsx
Batch 2.10.18.xlsx
...
Batch 31.10.18.xlsx
如您所见,它们具有以下模式:Batch dd.mm.yy.xlsx
我需要按照文件名中的日期顺序处理它们。
到目前为止的代码:
private void processFiles(string BatchFilePath)
{
IOrderedEnumerable<string> fileEntries =
Directory.GetFiles(BatchFilePath, "Batch *.xlsx")
.OrderBy(f => GetFileDay(f));
foreach (string fileName in fileEntries)
{
Console.WriteLine("Processing File " + Path.GetFileName(fileName));
// Code that read and process files
}
}
private int GetFileDay(string file)
{
string s1= file.Substring(7, 2);
if (s1.Substring(1) == ".")
s1 = s1.Substring(0, 1);
return int.Parse(s1);
}
该代码不起作用。它仍然给我提供名称顺序错误的文件,如下所示:
Batch 25.10.18.xlsx
Batch 22.10.18.xlsx...
Batch 9.10.18.xlsx
Batch 3.10.18.xlsx
...
最佳答案
将字符串(例如“1.10.18”)解析为真实的DateTime
(2018-10-01):
DateTime GetFileDay(string fileNameOrPath)
{
string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileNameOrPath);
return DateTime.ParseExact(fileNameWithoutExt.Replace("Batch ", ""), "d.M.yy", null);
}
关于c# - 对目录中的文件名进行排序,给出错误排序的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53113039/