c# - 对目录中的文件名进行排序,给出错误排序的结果

标签 c# linq directory

我的目录中有文件,文件名如下:

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/

相关文章:

c# - 对十六进制字符串进行 XOR

C# Web API LINQ 实体查询 - 将 AnonymousType 转换为类对象

c# - 调试 Http 触发器 Azure Function VS 2017

c# - 如何在 Asp.Net 的服务器端使用 JavaScript 对象?

c# - 检查列表是否包含多个指定值

c# - 按多个表分组并仍然可以访问原始查询?

c++ - 从 QFileSystemModel 隐藏文件夹

windows - 在cmd中使用dir获取没有路径的文件夹名称

Powershell - 监控文件夹内容

c# - 从非托管代码调用托管 .NET 代码的最佳方式