Reputation: 569
Enviroment: Visual Studio 2010, Windows Forms Application.
Hi! I would like to rename (batch) some files... 1. I have (around 50 000 files): abc.mp3, def.mp3, ghi.mp3 I want: abc1.mp3, def1.mp3, ghi1.mp3
2. I have (around 50 000 files): abc.mp3, def.mp3, ghi.mp3 I want: 1abc.mp3, 1def.mp3, 1ghi.mp3
Something similar...
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowDialog();
string[] mp3Files = Directory.GetFiles(folderDlg.SelectedPath, "*.mp3");
string[] newFileName = new string[mp3Files.Length];
for (int i = 0; i < mp3Files.Length; i++)
{
string filePath = System.IO.Path.GetDirectoryName(mp3Files[i]);
string fileExt = System.IO.Path.GetExtension(mp3Files[i]);
newFileName = mp3Files[i];
File.Move(mp3Files[i], filePath + "\\" + newFileName[1] + 1 + fileExt);
}
But this code doesn't work. Error here... newFileName = mp3Files[i];
And I cannot to convert it correctly.
Thank You!
Upvotes: 1
Views: 1469
Reputation: 117019
Try this code instead:
Directory.GetFiles(folderDlg.SelectedPath, "*.mp3")
.Select(fn => new
{
OldFileName = fn,
NewFileName = String.Format("{0}1.mp3", fn.Substring(fn.Length - 4))
})
.ToList()
.ForEach(x => File.Move(x.OldFileName, x.NewFileName));
Upvotes: 2
Reputation: 4893
Fastest option would be use direct OS renaming function. Use process object to run shell CMD with /C switch. Use the "ren" command line renaming.
Process cmd = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = @"/C REN c:\full\path\*.mp3 c:\full\path\1*.mp3"
}
};
cmd.Start();
cmd.WaitForExit();
//Second example below is for renaming with file.mp3 to file1.mp3 format
cmd.StartInfo.Arguments = @"/C REN c:\full\path\*.mp3 c:\full\path\*1.mp3";
cmd.Start();
cmd.WaitForExit();
Upvotes: 4
Reputation: 13582
as friends discussed in the comments, you can either declare newFileName as a simple string (instead of array of strings) or use code below if you intend to use array:
newFileName[i] = mp3Files[i];
and since you are using for loop you'd better use string and not array of strings.
Upvotes: 0