Reputation:
I am writing a .NET Framework (C#) app. I have a directory which contains files and folders. Each folder has a 3 digit number as its name. I want to find the folder name which has the highest value.
So far, I came up with the following code:
public void doCopyFiles()
{
string sourceDir = @"C:\Users\xyz\abc\gth";
var sorted = Directory.GetFiles(sourceDir, ".").OrderBy(path => int.Parse(Path.GetFileNameWithoutExtension(path)));
var lastFile = sorted.Last();
Console.WriteLine(lastFile);
}
However, this throws a System.FormatException, which says "input string not in expected format". I am assuming this is because there are other files present which have normal strings as their filename.
Are there any suggestions on how to fix this?
EDIT: After trying both solutions shown below, the same error is still persisting.
Upvotes: 0
Views: 589
Reputation: 38
Edited to reflect answers to comment question and suggestion.
public void doCopyFiles()
{
int highestFolder = int.MinValue;
string sourceDir = @"C:\Users\xyz\abc\gth";
var dirs = Directory.GetDirectories(sourceDir);
foreach(var value in dirs)
{
if(int.TryParse(value, out int result))
{
if(result > highestFolder)
{
highestFolder = result;
}
}
}
if(highestFolder != int.MinValue)
{
Console.WriteLine(highestFolder);
}
else //no folder with int names were found
{
//error message
}
}
Upvotes: 2
Reputation: 12561
The fix for your implementation would be to first select the file names that are all numerals. This can be done by checking for a match with the regex \d+
var sorted = Directory.GetFiles(sourceDir, ".")
.Where( path => Regex.IsMatch(Path.GetFileNameWithoutExtension(path), @"\d+"))
.OrderBy(path => int.Parse(Path.GetFileNameWithoutExtension(path)));
Assuming your numeric file names are zero padded (001 instead of 1), you can sort without parsing the value. Based on the numeric values of the ASCII characters, your numbered files should be listed in order and first in the sorted list.
Upvotes: 0