如何使目录数组排序与硬盘显示的自然顺序一致?
保存目录的自然排序问题解决
问题现象
获取保存目录后,数组排序结果不符合预期:排序后为0,1,10,11...19,2,20...26,3,4...9,但硬盘上的目录呈现正确的自然排序0,1,2...9,10,11...27。
目录名称示例:C:/Users/test/AppData/LocalLow/DefaultCompany/my game/Saved Games\SaveSlot0 SavedGameSlot_1920x1080_2023-06-15_14-04-08,后续依次为SaveSlot1、SaveSlot10等。
原代码及无效尝试
原代码片段:
string savedGamesFolder = string.Format("{0}/Saved Games", Application.persistentDataPath); if (!Directory.Exists(savedGamesFolder)) { Directory.CreateDirectory(savedGamesFolder); } string[] directories = Directory.GetDirectories(savedGamesFolder); Array.Sort(directories, new NaturalSortComparer());
尝试的NaturalSortComparer类无法得到正确排序:
public class NaturalSortComparer : IComparer<string> { public int Compare(string a, string b) { return StringComparer.Create(System.Globalization.CultureInfo.CurrentCulture, true).Compare(a, b); } }
有效解决方案
使用调用系统API的MyComparer类,可实现与硬盘一致的自然排序:
public class MyComparer : IComparer<string> { [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); public int Compare(string psz1, string psz2) { return StrCmpLogicalW(psz1, psz2); } }
使用方式:
string[] directories = Directory.GetDirectories(savedGamesFolder); Array.Sort(directories, new MyComparer());
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

