0

I have a program, written with net471 and uses Directory.GetFiles.

Now we want to convert it to .NET Core and run it on Linux.
When we do this, we get a different order of files.

I know what the docs say:

The order of the returned file names is not guaranteed

But until we moved to Linux, files were fixed order.

We want to keep this order, do we need to write a comparer ourselves, or does one already exist?

Rules:

  • Underscore after without: file.txt -> file_en.txt.
  • Name with number after without: file.txt -> file1.txt
  • Number before Underscore: file1.txt -> file_en.txt
  • Alphabetical numbers: 10.txt -> 3.txt
  • Ignore case: AA.txt -> ab.txt -> ZZ.txt

If there is a comparer for that, we need it to be an OS agnostic.

baruchiro
  • 5,088
  • 5
  • 44
  • 66

2 Answers2

4

The order of the files isnt guaranteed in .net framework either (from the .net framework docs https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.1):

The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required.

Your application's behaviour should be no better or worse than it is now. As the docs suggest, you can use Sort to guarantee the order of the files. Sort takes an implementation of IComparer so you can implement the rules above if you really need to ensure that things are returned in this order.

richzilla
  • 40,440
  • 14
  • 56
  • 86
2

According to How to compare strings in C# (and the Try.NET) you need to use OrdinalIgnoreCase to get these rules.

For example:

var files = Directory.GetFiles(folderName);
Array.Sort(files, StringComparer.OrdinalIgnoreCase);
baruchiro
  • 5,088
  • 5
  • 44
  • 66
  • Doesn't work for numerical comparisons, e.g. `10.txt -> 3.txt` (as per OPs requirement) – Matthew Watson Nov 25 '19 at 09:51
  • 1
    @MatthewWatson - it does work, because OP wants numbers to be sorted alphabetically. And with `OrdinalIgnoreCase` the `string` `"10"` is "less than" `"3"`. – Corak Nov 25 '19 at 09:58
  • Ah I was reading `10.txt -> 3.txt` as meaning that `10` should follow `3` (I was reading the `>` as "greater than"). – Matthew Watson Nov 25 '19 at 15:04
  • @Matthew Watson What do you recommend me to write instead of `->` – baruchiro Nov 25 '19 at 16:08
  • @baruchiro It's fine as you wrote it really - I just didn't parse it properly :) I suppose you could say that you require `"10.txt" < "3.txt"` (using `<` as "less than"), but it's not really necessary. – Matthew Watson Nov 26 '19 at 12:48