zoukankan      html  css  js  c++  java
  • C#文件名的自然序API与通过IComparer<T>接口实现FileInfo的排序

    有Windows资源管理器中文件名如下:

    1你好.txt 、2你好.txt、11你好.txt

    使用C#  DirectoryInfo.GetFiles获得FileInfo[]信息的排序会是如下情况:

    1你好.txt 、11你好.txt、2你好.txt

    这不符合我们的使用习惯,可以借助Windows的API,在获取FileInfo[]之后进行自然序排序。代码如下:

     public class StringAPI
        {
            [SuppressUnmanagedCodeSecurity]
            internal static class SafeNativeMethods
            {
                [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
                public static extern int StrCmpLogicalW(string psz1, string psz2);
            }
    
            public sealed class NaturalStringComparer : IComparer<string>
            {
                public int Compare(string a, string b)
                {
                    return SafeNativeMethods.StrCmpLogicalW(a, b);
                }
            }
    
            public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo>
            {
                public int Compare(FileInfo a, FileInfo b)
                {
                    return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name);
                }
            }

    调用方法如下:

    Win32API.StringAPI.NaturalFileInfoNameComparer cp = new Win32API.StringAPI.NaturalFileInfoNameComparer();
    Array.Sort(fileInfos, (FileInfo x, FileInfo y) => cp.Compare(x, y));
  • 相关阅读:
    Python并发编程之多进程(实战)
    ThreadPoolExecutor源码分析
    JDK 1.8 JVM的变化
    JDK1.8 hashMap源码分析
    Spring解决循环依赖
    spring
    实现一个可重入锁和不可重入锁
    B树与B+树
    WebMagic
    Java高频面试题
  • 原文地址:https://www.cnblogs.com/yzhyingcool/p/14763103.html
Copyright © 2011-2022 走看看