I´m not able to solve my problem despite browsing through variety of topics in forum. I have a folder where are pdf files in sequence, e.g. WR 11.pdf, WR 16.pdf, WR 21.pdf, WR 22.pdf and WR 23.pdf. I need to save .pdf file automatically as WR 24.pdf (generally existing file with highest No. in folder + 1). Any ideas, how to proceed?
You might assume that most recent file has the highest number, you might sometimes want to overwrite, etc.
Here, you won’t overwrite. The searchPattern will be "WR*.pdf" and destinationDirectory is the directory you’re working with.
The idea is to count the number of file matching searchPattern and use that number + 1 to obtain the new filename candidate. If the filename already exists, we compute a new filename candidate by adding 1 more until the filename is “free”.
Variables
prefix (String) = "WR"
destination (String)
searchPattern (String)
files (Array of String)
i (Int32)
fileName (String)
Workflow
// Assign
searchPattern = String.Format("{0}*.pdf", prefix)
// Assign
files = Directory.GetFiles(destinationDirectory, searchPattern)
// Assign
i = files.Length
// Do While
Do:
// Assign
i = i + 1
// Assign
fileName = String.Format("{0} {1}.pdf", prefix, i)
// Assign
destination = Path.Combine(destinationDirectory, fileName)
While:
File.Exists(destination) // Or files.Contains(destination)
I´m trying your solution, but got stuck with regex and read of decimal No. in argument with error message. I think it´s related to a variable type somehow.
EDIT: the error is from the ForEach’s TypeArgument set to Object. Change it to String to resolve it. In addition, the trim in unnecessary as you capture only digits.
@Peter_Carnogursky There might be a reason that logic didn’t went into For Each loop. you can use Write Line/Message box to check whether it was executed or not
I tried your solution with the result below. So if there are 3 files in the folder, your solution offers to name next file Monthly report 4.pdf. But my intention is to rename Monthly report actual.pdf as Monthly report 25.pdf in this case to continue in order. If the last file would be Monthly report 35, I´d like to rename Monthly report actual.pdf as Monthly report 36.pdf. Sorry if I misled you with my first post.
Yes, Arpit_Kesharwani approach is better suited. Did you try the three line implementation I posted? I see that the file names are different, please adapt the searchPattern accordingly.
I tried your proposal right now and it returns empty string like with Arpit logic. I see both of your approaches either to trim value or set a function, but I´m how to solve this challenge