According your use case you might want to use temporary directories, etc. instead of renaming directly the files, or use temporary names to avoid pattern clashes, etc.
You can also use a datatable instead of a dictionary, for example if you want to maintain the oldName/newName in an excel file; convert it to a dctionary afer load or adapt accordingly.
You can keep the logic into the loop in its own process for reuse and clarity. You can organise it better but for the sake of the explanation, I put it all together.
Workflow Overview:
Initial Setup: Assign activities to set folder path, dictionary, and regex.
Loop Through Files: A For Each activity to process all files.
Prefix Handling: Regex match and dictionary lookup with If conditions.
File Counting: Use Directory.GetFiles
Renaming: Use string formatting.
Move Files: Rename files with the Move File activity.
Step-by-step
Initialise the folder path:
Use an Assign activity:
folderPath = "C:\Your\Folder\Path"
Create a dictionary for prefix-to-new-name mapping:
Use an Assign activity to initialise a dictionary of type Dictionary(Of String, String):
prefixToRoot = New Dictionary(Of String, String) From {
{"ABC", "A"},
{"DEF", "D"}
}
Get the list of files in the folder:
Use an Assign activity:
files = Directory.GetFiles(folderPath)
(Variable type: String[])
Set up a regular expression to extract prefixes:
Use an Assign activity to initialise the Regex:
prefixRegex = New System.Text.RegularExpressions.Regex("^[a-zA-Z]+")
(Variable type: Regex)
Iterate over the files:
Add a For Each activity to loop through the files:
Type of item: String
Variable name: file
Extract the prefix with Regex:
Inside the loop:
Use an Assign activity to get the file name without the extension:
fileName = Path.GetFileNameWithoutExtension(file)
Use another Assign activity to extract the prefix:
match = prefixRegex.Match(fileName)
(Variable type: Match)
Add an If activity to check if the prefix was successfully extracted:
match.Success
Check if the prefix exists in the dictionary:
Add another If activity to verify:
prefixToRoot.ContainsKey(match.Value)
True: Proceed with the following steps.
False: Add a Log Message activity to indicate that the file is being skipped.
Count existing files for the prefix in the folder:
Use an Assign activity to find matching files:
Handle files without valid prefixes or missing mappings:
For files that don’t match the Regex or whose prefixes aren’t in the dictionary, add a Log Message activity to skip them. (or fail loudly, or handle it the way you want)