Reputation: 1550
EDIT - Revised the title of my post to make it more relevant to the problem.
I have folders that may or may not contain subfolders that start with "REV". If there are subfolders that start with "REV" they are followed by an integer value padded with leading zeros. (ie: REV010 or REV003).
My goal here is to:
When I debug the code (below), it cannot seem to find the REV003 folder (The folder definitely exists in the path).
Is something wrong with my LINQ statement in finding the folder?
Also, if there is an easier procedure to achieve the same thing - I'm definitely open for it! Thanks!
int nextRev = 0;
List<int> listOfRevs = new List<int>();
IEnumerable<string> revFolders = Directory.GetDirectories(destDirName, "*REV*", SearchOption.AllDirectories).Where(f => f.StartsWith("REV"));
foreach (var rev in revFolders)
{
Console.WriteLine(int.Parse(rev.Replace("REV", "")));
listOfRevs.Add(int.Parse(rev.Replace("REV", "")));
}
if (listOfRevs.Count > 0)
{
nextRev = listOfRevs.Max();
Console.WriteLine(nextRev);
nextRev++;
}
revFolder = "REV" + nextRev.ToString("000");
Console.WriteLine("New Folder: " + revFolder);
** UPDATE ** Thanks to NetMage the problem was fixed, however I still had a few bugs. Here's the working code:
string revf = "";
int nextRev = 0;
List<int> listOfRevs = new List<int>();
IEnumerable<string> revFolders = Directory.GetDirectories(destDirName, "REV*", SearchOption.AllDirectories);
foreach (var rev in revFolders)
{
if (rev.Contains("REV"))
{
revf = rev.Split('\\').Last();
listOfRevs.Add(int.Parse(revf.Replace("REV", "")));
}
}
if (listOfRevs.Count > 0)
{
nextRev = listOfRevs.Max();
nextRev++;
}
revFolder = "REV" + nextRev.ToString("000");
Upvotes: 0
Views: 146
Reputation: 26926
Change your directory search to
IEnumerable<string> revFolders = Directory.GetDirectories(destDirName, "REV*", SearchOption.AllDirectories);
Based on the results from this, you will to change the maximum finding code - I would use LINQ:
var maxREV = Directory.GetDirectories(destDirName, $"REV*", SearchOption.AllDirectories)
.Select(d => Int32.TryParse(Path.GetFileName(d).Substring(3), out int num) ? num : (int?)null)
.Where(n => n.HasValue)
.Select(n => n.Value)
.Max();
var revFolder = "REV" + (maxREV+1).ToString("000");
Console.WriteLine("New Folder: " + revFolder);
I put in some error handling to skip files that don't have an integer after "REV".
Upvotes: 1