简体   繁体   中英

Renaming the Group of Files in C# (Windows Forms Application)

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!

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();

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM