Copy and Renaming files

Windows 11 / XOJO 2024r1.1
I have a folder with a few thousand files with names starting with a 4 digit number.
For example : ‘2154 Sweet dreams.mid’
I would like to rename all these files without the leading 4 digit number.
‘2145 Sweet Dreams.mid’ would become ‘Sweet Dreams.mid’.
Best options would be to copy each file to another folder with his new name.

I cannot figure out how I need to do this .
Any help would be very welcome.

Thanks
Regards
Etienne

I can manage to read all the files in a folder and put them in a Listbox for example.
The only problem is to copy and rename each file to another folder, or renaming and keep in the same folder (is more dangerous because of the eventually lost of the files).

It would probably be fastest using a shell to DOS, but this code will do the job

Var x As folderitem = specialfolder.Desktop.child("files")  //or wherever
Var f As folderitem
For Each f In x.Children
  f.name = f.name.Middle(5)
Next

If you want to copy and rename, you could try

Var x As folderitem = specialfolder.Desktop.child("files")  //or wherever
Var f As folderitem
For Each f In x.Children
f.CopyTo specialfolder.ApplicationData.child("target").child( f.name.Middle(5)   )
Next
1 Like

Just be aware of collisions. Say you have, among all the files, those filenames: “2154 Sweet dreams.mid” and “5937 Sweet dreams.mid”, both methods would fail at the 2nd file, because they end up having the same file name.
You have at least three options to solve this:
1: if you know all file names are unique, just do it that way.
2: before assigning the name (or copying), check whether an item already exists in the same folder (if f.parent.child(NewName).exists then) and either (1) check which was the last number assigned to that name and add 1 (a dictionary to keep the last number of each already-treated-file name can help) or (2) add a random number at the end of the filename (before the extension).
3: perform 3 loops: the first collects the file names (i.e. store each file with the original file name, using preferably a dictionary, or two arrays), the second checks for duplicates and assigns a number to the same names (e.g. “Sweet dreams.mid”, “Sweet dreams 2.mid”, “Sweet dreams 3.mid”) and the third renames the files.

For number 3, it’s important to separate in several loops. Don’t intend to rename on the fly, because doing so may rearrange the list of files and you end up dealing twice with some files and never with others.
This has to be complex if your setup is complex as well. Otherwise, no.

2 Likes

Thanks Jeff and Arnaud.
I will give it a tr.
Regards
Etienne