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));
  • 相关阅读:
    一月5日
    一月5日
    面试java工程师的自我介绍(模拟篇)
    Spring Boot Jpa 介绍
    spring+redis做缓存使用
    Spring Boot Web 开发详解
    thymeleaf+spring的简单搭建
    如何搭建 Spring boot
    通用baseDao
    pagehelper的使用
  • 原文地址:https://www.cnblogs.com/yzhyingcool/p/14763103.html
Copyright © 2011-2022 走看看