none
Windows explorer custom file sort name order RRS feed

  • Question

  • Hi,

    Where would I start if I wanted to create a program to adjust the order in which windows lists files in explorer when ordered by Name? I would like the files to be sorted by a unique number at the end of the file name rather than using the generic windows sorting algorithm which orders the names in alphabetical/numerical order from the start of the file name. Is this possible?

    EXAMPLE-0001.pdf
    ANEXAMPLE-0002.pdf
    ANOTHEREXAMPLE-0003.pdf

    Thanks

    Friday, January 18, 2019 9:31 PM

All replies

  • Hi,

    if you have a list with the strings, you can do something like this:

            static void Main(string[] args)
            {
                var list = new List<string>
                {
                    "ANEXAMPLE-0002.pdf",
                    "EXAMPLE-0001.pdf",
                    "ANOTHEREXAMPLE-0003.pdf"
                };
                list = list.OrderBy(x => GetInt(x)).ToList();
            }
            public static int GetInt(string str)
            {
                var match = Regex.Match(str, @"(?<=\-)(.*?)(?=\.)");
                if (!Int32.TryParse(match?.Value, out int i))
                    throw new Exception();
                return i;
            }

    Greetings, Chris


    • Edited by DerChris88 Friday, January 18, 2019 11:04 PM
    Friday, January 18, 2019 11:01 PM
  • Hi mark_246,

    If the file name is fixed format as you mentioned, please try the following method.

    DirectoryInfo dir = new DirectoryInfo(@"yourFileFolderPath");
    FileInfo[] files = dir.GetFiles();          
    Array.Sort(files, (x, y) => x.Name.Substring(x.Name.Length - 8, 4).CompareTo(y.Name.Substring(y.Name.Length - 8, 4)));

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 23, 2019 2:09 AM
    Moderator