Click on the banner to learn about and purchase my database training on Azure

CSharp (C #) - How to sort files returned by DirectoryInfo.GetFiles using Natural Sort

Views: 1.076 views
Reading Time: 4 minutes

Hello people,
Good Morning!

In this post I will take a very simple approach to something that many .NET developers are looking for on the internet, as I sought this solution myself, but which is a little tricky to find because most of the posted solutions do not work.

My problem was that I use a C # function a lot in my CLR to list files from a directory (I had already posted this function in the post SQL Server - How to list, read, write, copy, delete and move files with CLR (C #)), but the fact that the files are not sorted correctly always bothered me, and I decided to improve it.

Example of current usage:
CSharp sort sorting DirectoryInfo.GetFiles by name natural sort 1

Even if you use an ORDER BY clause to try to sort, it won't work, because SQL Server will do string sorting using alphanumeric sorting.

How the alphanumeric string sorting algorithm works
This type of algorithm uses ASCII code to sort data by comparing character by character until the string ends or the ASCII code of one string is shorter than the other. Thus, in a comparison between 100 File and 20 File, the comparison will be made as follows:

  • Each character of the word "File" will be compared between the 2 strings. As they are the same, the algorithm will proceed to the rest of the string
  • The character "1" will be compared with the character "2". As it is smaller, the sorting ends there, placing “File 100” before “File 20”

How the Natural Sort String Sorting Algorithm Works
Just as I am uncomfortable with this ordering, which is the standard for the vast majority of programming languages, many people also dislike the “100” before “2000” and to give a more “humanized” view, the Natural Sort algorithm was created, which separates numerical characters from letters, and sorts them separately. The numbers are compared numerically (where 100 is greater than 20), and the strings he continues using the ASCII code.

To implement the Natural Sort algorithm, I found code in the James McCormack blog to create an ICompare class in C # and thus sort my files in my function (and any other list of files you need to sort).

View Source Code for ICompare Class

Now I need to change my file listing function (I also include a boolean flag to list files within subdirectories or not) and include an OrderBy function through the LINQ library.

In this excerpt:

I changed to this snippet:

And with that, our problem was solved, where we have the following result:
CSharp sort sorting DirectoryInfo.GetFiles by name natural sort solved

View Full Source Code for this Function

Thank you so much for visiting and see you next post!