例如,我有这样的文件夹结构:
驾驶C:
| - 全球
| ------文件夹
| ------ | ---- FileA.dll
| ------ | ---- FileB.dll
| ------ | ---- FileA_1.dll
| ------ CodeFolder
| ------ | ---- FildeCode.dll
| ------ | ---- FildeCode_1.dll
| ------ ContentFolder
| ------ | ---- ScriptsFolder
| ------ | -------- FileScripts.dll
| ------ | -------- FileScriptsA.dll
| ------ | -------- FileScripts_1.dll
我想获取列表文件路径,但每个文件都是唯一且不同的:
此处结果(此处的顺序被忽略):
C:\全球\文件夹\ FileA_1.dll
C:\全球\文件夹\ FileB.dll
C:\全球\ CodeFolder \ FileCode_1.dll
C:\全球\ ContentFolder \ ScriptFolder \ FileScriptsA.dll
C:\全球\ ContentFolder \ ScriptFolder \ FileScripts_1.dll
我怎么做C#?
答案 0 :(得分:2)
您需要自然排序文件名,因此您可以导入StrCmpLogicalW函数。您必须为项目启用不安全的代码。
internal sealed class NaturalStringComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
public static readonly NaturalStringComparer Default = new NaturalStringComparer();
public int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
}
然后,您可以使用以下代码获取文件列表。
string[] filePathList = Directory.GetFiles(@"C:\Global\", "*.dll", SearchOption.AllDirectories)
.Select(path => new
{
Path = path,
Name = Path.GetFileName(path),
TruncatedName = Regex.Replace(Path.GetFileName(path), @"(_\d+)+(?=\.dll$)", string.Empty)
})
.GroupBy(file => file.TruncatedName)
.Select(group => group.OrderByDescending(file => file.Name, NaturalStringComparer.Default).First().Path)
.ToArray();
答案 1 :(得分:1)
为什么不这样做(或者我在这里遗漏了什么)
string[] directories = Directory.GetFiles("directoryPath", "*.*", SearchOption.AllDirectories);