Rename some files in a folder

前端 未结 6 824
遇见更好的自我
遇见更好的自我 2020-12-05 05:59

I have a task of changing the names of some files (that is, adding id to each name dynamically) in a folder using C#.

Example: help.txt to 1help.txt

How can

6条回答
  •  时光说笑
    2020-12-05 06:57

    On .NET Framework 4.0 I use FileInfo.MoveTo() method that only takes 1 argument

    Just to move files my method looks like this

    private void Move(string sourceDirName, string destDirName)
    {
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        FileInfo[] files = null;
    
        files = dir.GetFiles();
    
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.MoveTo(temppath);
        }
    }
    

    to rename files my method looks like this

    private void Rename(string folderPath)
    {
       int fileCount = 0;
    
       DirectoryInfo dir = new DirectoryInfo(folderPath);
    
       files = dir.GetFiles();
    
       foreach (FileInfo file in files)
       {
           fileCount += 1;
           string newFileName = fileCount.ToString() + file.Name;
           string temppath = Path.Combine(folderPath, newFileName);
    
           file.MoveTo(temppath);
       }
    }
    

    AS you can see to Rename file it syntax is almost the same as to Move it, just need to modify the filename before using MoveTo() method.

提交回复
热议问题