当读取文件夹或者文件时,有时会遇到这样一个问题,文件夹或者文件的命名为1,2,3,4,5,6,7,8,9,10,11,12等,在电脑上面显示时,是按照递增的方式,可是当用C#来读取时,默认按照的顺序是1,10,11,12,2,20,21,3,4,5,6,7,8,9,如果对文件顺序要求很严格,这样明显不符合要求。那怎么对这样进行再次排序呢。
首先,介绍一个函数StrCmpLogicalW,这是字符串逻辑比较函数,在比较时,字符串里面的数字会转化为数值来比较,而不是文本。这是用StrCmpLogicalW比较后的顺序。具体请参考:https://msdn.microsoft.com/zh-cn/library/windows/desktop/bb759947(v=vs.85).aspx
C#中代码实现的方法:
1、创建类后接口
//自定义一个比较类,读取文件夹或者文件时用于正确排序
public class FileComparer : IComparer<string>
{
[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return StrCmpLogicalW(psz1, psz2);
}
}
首先需要导入StrCmpLogicalW,
[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
这两行代码实现导入,接着就是使用了。
2、文件夹排序
DirectoryInfo theFolder = new DirectoryInfo(folderBrower.SelectedPath);
DirectoryInfo[] subFolders = theFolder.GetDirectories();
subFolders = subFolders.OrderBy(x => x.Name, new FileComparer()).ToArray();
其中folderBrower.SelectedPath是读取的文件夹路径,根据实际会有不同。
这样实现文件夹的排序。先来看下之前的读取顺序
在调用StrCmpLogicalW后:
这才是我要的顺序。
3.文件排序
文件排序和文件夹排序是差不多的。
DirectoryInfo theFolder = new DirectoryInfo(folderBrower.SelectedPath);
FileInfo[] theFiles = NextFolder.GetFiles("*.bin");
theFiles = theFiles.OrderBy(y => y.Name, new FileNameComparerClass()).ToArray();
就不放图了。