Click to See Complete Forum and Search --> : Bulk rename files program in c#?


thisismyusername2010
February 14th, 2010, 09:19 PM
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?

rliq
February 14th, 2010, 09:32 PM
Yes.

File.Move( oldFileName, newFileName );


You may want to catch exceptions as some files could be locked.

Use:

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:

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.

thisismyusername2010
February 14th, 2010, 10:46 PM
I'm getting the error
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
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?

rliq
February 14th, 2010, 10:49 PM
oldFileName is just ONE of the items in the oldFileNames (notice the S on the end) array.
so...

foreach (String fileName in fileNames)
{
...
}

thisismyusername2010
February 14th, 2010, 10:57 PM
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)


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
{
}

rliq
February 14th, 2010, 11:00 PM
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...

thisismyusername2010
February 14th, 2010, 11:07 PM
It works perfectly! Thanks for the help!

rliq
February 14th, 2010, 11:09 PM
No worries, glad to see you worked it out. It reminds me... I need to rename all of my MP3's too!!