I have a directory with 40 files with names from 0 to 39 (for example), I am trying to get the file with the largest number in its name (which means I need to get \"39\") I
This is VB.NET to retrieve the highest numbered name. Changing the OrderByDescending key to x.LastWriteTime gets the newest file.
Dim OldName As String = String.Empty
Dim DI As New IO.DirectoryInfo("C:\")
For Each FI As IO.FileInfo In DI.GetFiles("*.*").OrderByDescending(Function(x) x.Name)
OldName = FI.FullName
Exit For
Next
There is a native function in windows StrCmpLogicalW that will compare in strings numbers as numbers instead of letters. It is easy to make a comparer that calls out to that function and uses it for it's comparisons.
public class StrCmpLogicalComparer : Comparer<string>
{
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public override int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
}
Here is a example program that will show the diffrence between the default sort and the StrCmpLogicalW
sort
class Program
{
static void Main()
{
List<string> items = new List<string>()
{
"Example1.txt", "Example2.txt", "Example3.txt", "Example4.txt", "Example5.txt", "Example6.txt", "Example7.txt", "Example8.txt", "Example9.txt", "Example10.txt",
"Example11.txt", "Example12.txt", "Example13.txt", "Example14.txt", "Example15.txt", "Example16.txt", "Example17.txt", "Example18.txt", "Example19.txt", "Example20.txt"
};
items.Sort();
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.WriteLine();
items.Sort(new StrCmpLogicalComparer());
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
which outputs
Example1.txt
Example10.txt
Example11.txt
Example12.txt
Example13.txt
Example14.txt
Example15.txt
Example16.txt
Example17.txt
Example18.txt
Example19.txt
Example2.txt
Example20.txt
Example3.txt
Example4.txt
Example5.txt
Example6.txt
Example7.txt
Example8.txt
Example9.txt
Example1.txt
Example2.txt
Example3.txt
Example4.txt
Example5.txt
Example6.txt
Example7.txt
Example8.txt
Example9.txt
Example10.txt
Example11.txt
Example12.txt
Example13.txt
Example14.txt
Example15.txt
Example16.txt
Example17.txt
Example18.txt
Example19.txt
Example20.txt
It is only logical that they would be sorted that way, you would bring in some semantics to sort it by number, namely parse all the file names to numbers, then sort the files by that.
Something like
files.OrderBy(path => Int32.Parse(Path.GetFileNameWithoutExtension(path)))
Use Last()
to get the file with the highest number.