Reputation: 21
Ex. If I created a folder with a folder name of IMG10001 but it was already exist in the target directory. The code below will make the folder name to IMG10001-1 but what I like to accomplish is to increment the folder name to IMG10002 if IMG10001 already exist in the target directory.
string destinDir = dirPath + "\\" + this.Batch.BatchName;
int x = 0;
if (Directory.Exists(destinDir))
{
do
{
x++;
destinDir = dirPath + "\\" + this.Batch.BatchName + "-" + x.ToString();
} while (Directory.Exists(destinDir));
}
System.IO.Directory.Move(root,destinDir);
Upvotes: 1
Views: 1523
Reputation: 3278
you can extract integer part from your string using Regex
and increment it as
string YourString = "IMG10001";
int IntegerPart = Convert.ToInt16(Regex.Match(s, "\\d+").ToString());
IntegerPart++;
Upvotes: 1
Reputation: 656
Assuming that BatchName always starts with "IMG", you can split the number out of the file. To make sure you get the highest number, loop through all the files and store the highest number found.
Once you have found the highest number, increment it by 1 and rebuild you filename ("IMG" + newNumber).
Upvotes: 1
Reputation: 657
//regular expression will work
Regex reg = new Regex("IMG(\\d+)$");
Match m = reg.match(this.Batch.BatchName);
int num = 10001;
if(m.success){
int.tryParse(m.Groups[1].value,out num);
}
Return string.format("IMG{0}",num);
I just write these code in the input box, I haven't tried. but I think it should work
Upvotes: 2