You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使目录数组排序与硬盘显示的自然顺序一致?

保存目录的自然排序问题解决

问题现象

获取保存目录后,数组排序结果不符合预期:排序后为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:42:47