I have a project on .net code on which I am working with files.
I have a lot of folders and the naming convention is like this :
pdf(1)
pdf(2)
pdf(3)
pdf(4)
pdf(5)
What I have to do is when I insert a new folder, it's new name should be (# of folders that exist 1)
And this code does that very well:
string FileDirectory = "C\\test\\myfiles\\";
string FileName = "pdf";
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(FileDirectory);
FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" FileName "*");
int i = filesAndDirs.Length;
if (i>0)
{
i ;
Directory.CreateDirectory(FileDirectory '\\' FileName "(" i ")");
}
Now, although this code works alright, there is this scenario when it doesn't. E.g, existing files are:
pdf(1)
pdf(2)
pdf(5)
pdf(6),
it will try to create a new folder,(# of folders i) and that would be "pdf(5)" but "pdf(5)" already exists!
Now my question is: how can I get the highest "index" of the existing folders (6) on this example, and create a new folder pdf(6) 1 ?
CodePudding user response:
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
List<string> files = new List<string>{"pdf(1)","pdf(2)","pdf(3)"};
List<string> nums = new List<string>();
foreach (var file in files)
{
var str = file.Substring(file.IndexOf("(")).Replace(")","").Replace("(","");
nums.Add(str);
}
var fileNums = nums.ConvertAll(x=>x);
var lastfileNo = fileNums.OrderByDescending(x => x).FirstOrDefault();
}
}
}
there might be another way around also
first loop through files and store it to list of string then convert all into an int, if you wish not to convert then it's fine then order by descending and find the first one