can't sort files from folder in String[] Array

后端 未结 4 929
既然无缘
既然无缘 2021-01-28 04:06

my project is about recording screen as sequence of images then instead of make it as video i planed to load all image directories to list and use timer to view them image by im

4条回答
  •  囚心锁ツ
    2021-01-28 04:14

    You need to use a "natural sort order" comparer when sorting the array of strings.

    The easiest way to do this is to use P/Invoke to call the Windows built-in one, StrCmpLogicalW(), like so (this is a compilable Console application):

    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System.Security;
    
    namespace ConsoleApp1
    {
        [SuppressUnmanagedCodeSecurity]
        internal static class NativeMethods
        {
            [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
            public static extern int StrCmpLogicalW(string psz1, string psz2);
        }
    
        public sealed class NaturalStringComparer: IComparer
        {
            public int Compare(string a, string b)
            {
                return NativeMethods.StrCmpLogicalW(a, b);
            }
        }
    
        sealed class Program
        {
            void run()
            {
                string[] filenames =
                {
                    "0.jpeg",
                    "1.jpeg",
                    "10.jpeg",
                    "11.jpeg",
                    "2.jpeg",
                    "20.jpeg",
                    "21.jpeg"
                };
    
                Array.Sort(filenames); // Sorts in the wrong order.
    
                foreach (var filename in filenames)
                    Console.WriteLine(filename);
    
                Console.WriteLine("\n");
    
                Array.Sort(filenames, new NaturalStringComparer()); // Sorts correctly.
    
                foreach (var filename in filenames)
                    Console.WriteLine(filename);
            }
    
            static void Main(string[] args)
            {
                new Program().run();
            }
        }
    }
    

    NOTE: This example is based on code from this original answer.

提交回复
热议问题