在我的硬盘上,例如:
目录1
目录2
目录3
目录4
……
我的代码是:
DirectoryInfo dInfo = new DirectoryInfo(AutomaticsubDirectoryName);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
so in subdirs
我获取了所有目录,但它们的顺序与硬盘上的顺序不同。
我怎样才能对它们进行排序,以便它们出现在subdirs
它们在我的硬盘上的顺序相同吗?
解决了这个问题:
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>
{
int i = 0;
if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))
{
string z = d.Name.Substring(("Lightning ").Length);
string f = z.Substring(0, z.IndexOf(" Length"));
if (Int32.TryParse(f, out i))
return i;
else
return -1;
}
else
return -1;
}).ToArray();
工作完美。
Windows使用的字符串比较函数暴露给大家使用。因此,您需要一点点 pinvoke 才能获得与 Explorer 使用的完全相同的排序顺序。将其包装在 IComparer 中,以便您可以将其传递给 Array.Sort() 或 OrderBy() Linq 子句:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class LogicalComparer : IComparer<string> {
public int Compare(string x, string y) {
return StrCmpLogicalW(x, y);
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(string s1, string s2);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)