class FileNameSort : IComparer
{
[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int StrCmpLogicalW(string param1,string param2);
//前后文件名进行比较
public int Compare(object x, object y)
{
if (x == null && y == null) return ;
if (x == null) return -;
if (y == null) return ;
return StrCmpLogicalW(x.ToString(), y.ToString());
} }
使用代码:
/// <summary>
/// 按照名字排序,用自定义比较器排序
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static FileInfo[] GetAllFilesBySort(string path)
{
FileInfo[] files=null;
DirectoryInfo folder = new DirectoryInfo(path);
if (folder.Exists)
{
files = folder.GetFiles();
// 文件名的升序
Array.Sort(files, new FileNameSort());
}
return files;
}
//
// 摘要:
// 比较两个对象并返回指示一个是否小于、 等于还是大于另一个值。
//
// 参数:
// x:
// 要比较的第一个对象。
//
// y:
// 要比较的第二个对象。
//
// 返回结果:
// 一个有符号整数,指示 x 和 y 的相对值,如下表所示。值 含义 小于零 x 小于 y。零 x 等于 y。大于零 x 大于 y。
//
// 异常:
// T:System.ArgumentException:
// 既不 x ,也不 y 实现 System.IComparable 接口。- 或 - x 和 y 的类型不同,既没有一个可以处理与其他的比较。
int Compare(object x, object y);