Bulk rename files program in c#?
Is it possible to make a program that takes files and can take something out of their original name? I.E. the file 1.txt, that file 2.txt, this file 3.txt, changed to take "this" out and only say the 1.txt, that 2.txt, and this 3.txt ?
If it's possible, how would I go about doing that?
Re: Bulk rename files program in c#?
Yes.
Code:
File.Move( oldFileName, newFileName );
You may want to catch exceptions as some files could be locked.
Use:
Code:
String[] oldFileNames = Directory.GetFiles( folderName, "*file*.txt");
To get a list of all of the text files that contain the word "file" as in your example. Then for each of the filenames in that loop:
Code:
String newFileName = oldFileName.Replace("file", String.Empty);
Be careful that the word "file" is not in the path to the file. I'm sure with some experimenting, you'll work it out from what I have said.
Re: Bulk rename files program in c#?
I'm getting the error
Code:
Error 1 'System.Array' does not contain a definition for 'Replace' and no extension method 'Replace' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
for the line
Code:
String newFileName = oldFileName.Replace("file", String.Empty);
Am I suppose to turn oldFileName into a string instead of keeping it as an array? Or turn newFileName into an array?
Re: Bulk rename files program in c#?
oldFileName is just ONE of the items in the oldFileNames (notice the S on the end) array.
so...
Code:
foreach (String fileName in fileNames)
{
...
}
Re: Bulk rename files program in c#?
I have the following now and it shows no errors, will this code work? (I'm afraid of running it without knowing because I don't want to crash my whole computer if I messed it up)
Code:
String[] oldFileNames = Directory.GetFiles(@"C:\Users\comp\Desktop\file - Copy\", "*File*.mp3");
try
{
foreach (string s in oldFileNames)
{
String newFileName = s.Replace("File", String.Empty);
File.Move(s, newFileName);
}
}
catch
{
}
Re: Bulk rename files program in c#?
That should work.
Why not create a copy of the directory beforehand whilst you are testing, then you're sure not to lose anything. Ahh, silly me, by the look of the folder name, seems you already have ;)
Also, try it on a small directory with one or two mp3 files in it first...
Re: Bulk rename files program in c#?
It works perfectly! Thanks for the help!
Re: Bulk rename files program in c#?
No worries, glad to see you worked it out. It reminds me... I need to rename all of my MP3's too!!
Re: Bulk rename files program in c#?
To batch rename files I suggest to try KrojamSoft BatchRenameFiles program
Re: Bulk rename files program in c#?
Quote:
Originally Posted by
frankos
To batch rename files I suggest to try KrojamSoft BatchRenameFiles program
Please don't open old threads with spam.