简体   繁体   中英

Renaming files in folder c#

I have over 1000 files in a folder with names like abc_1, abc_2 ... abc_n

I want to delete this prefix 'abc_' from all the files. Any chance to not doing this manually because there are over 1000, and it will be a pain.

How can do this with c# ?

You can try with this code

DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess");
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
    File.Move(f.FullName, f.FullName.Replace("abc_","")); // Careful!! This will replaces the text "abc_" anywhere in the path, including directory names.
}

You can use File.Move and String.Substring(index) :

var prefix = "abc_";
var rootDir = @"C:\Temp";
var fileNames = Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories);
foreach(String path in fileNames)
{
    var dir = Path.GetDirectoryName(path);
    var fileName = Path.GetFileName(path);
    var newPath = Path.Combine(dir, fileName.Substring(prefix.Length));
    File.Move(path, newPath);
}

Note: Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); will search also subfolders from your root directory. If this is not intended use SearchOption.TopDirectoryOnly .

You can enumerate the file.

using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

Then, ForEach the string[] and create a new instance of the IO.File object.

Once you get a handle on a File, just call the Move method and pass in String.Replace("abc_", String.Empty).

I said Move because there is no direct Rename method in IO.File.

File.Move(oldFileName, newFileName);

Be mindful of the extension.

You should have a look at the DirectoryInfo class and GetFiles() Method. And have a look at the File class which provides the Move() Method.

File.Move(oldFileName, newFileName);

Following code will work, not tested though,

 public class FileNameFixer
    {
        public FileNameFixer()
        {
            StringToRemove = "_";
            StringReplacement = "";


        }
        public void FixAll(string directory)
        {
            IEnumerable<string> files = Directory.EnumerateFiles(directory);
            foreach (string file in files)
            {
                try
                {
                    FileInfo info = new FileInfo(file);
                    if (!info.IsReadOnly && !info.Attributes.HasFlag(FileAttributes.System))
                    {
                        string destFileName = GetNewFile(file);
                        info.MoveTo(destFileName);
                    }
                }
                catch (Exception ex)
                {
                    Debug.Write(ex.Message);
                }
            }
        }

        private string GetNewFile(string file)
        {
            string nameWithoutExtension = Path.GetFileNameWithoutExtension(file);
            if (nameWithoutExtension != null && nameWithoutExtension.Length > 1)
            {
                return Path.Combine(Path.GetDirectoryName(file),
                    file.Replace(StringToRemove, StringReplacement) + Path.GetExtension(file));
            }
            return file;
        }

        public string StringToRemove { get; set; }

        public string StringReplacement { get; set; }
    }

you can use this class as,

  FileNameFixer fixer=new FileNameFixer();
        fixer.StringReplacement = String.Empty;
        fixer.StringToRemove = "@@";
        fixer.FixAll("C:\\temp");

you can use a foreach iteration along with the File class from the System.IO namespace.

All its methods are provided for you at no cost here: http://msdn.microsoft.com/en-us/library/system.io.file%28v=vs.100%29.aspx

Total Commander可以重命名多个文件(您无需为每个小任务自行编写工具)。

string path = @"C:\NewFolder\";    
string[] filesInDirectpry = Directory.GetFiles(path, "abc*");
forearch(string file in filesInDirectory)
{
    FileInfo fileInfo = new FileInfo(file);
    fileInfo.MoveTo(path + "NewUniqueFileNamHere");
}

I like the simplicity of the answer with the most up-votes, but I didn't want the file path to get modified so I changed the code slightly ...

string searchString = "_abc_";
string replaceString = "_123_";
string searchDirectory = @"\\unc\path\with\slashes\";
int counter = 0;
DirectoryInfo d = new DirectoryInfo(searchDirectory);
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
    if (f.Name.Contains(searchString)) 
    {
        File.Move(searchDirectory+f.Name, searchDirectory+ f.Name.Replace(searchString, replaceString));
        counter++;
    }
}
Debug.Print("Files renamed" + counter);

This code enables user to replace a part of file name. Useful if there are many files in a directory that have same part.

using System;
using System.IO;

// ...
    static void Main(string[] args)
    {
        FileRenamer(@"D:\C++ Beginner's Guide", "Module", "PDF");

        Console.Write("Press any key to quit . . . ");
        Console.ReadKey(true);
    }

    static void FileRenamer(string source, string search, string replace)
    {
        string[] files = Directory.GetFiles(source);

        foreach (string filepath in files)
        {
            int fileindex = filepath.LastIndexOf('\\');
            string filename = filepath.Substring(fileindex);

            int startIndex = filename.IndexOf(search);
            if (startIndex == -1)
                continue;
            int endIndex = startIndex + search.Length;

            string newName = filename.Substring(0, startIndex);
            newName += replace;
            newName += filename.Substring(endIndex);

            string fileAddress = filepath.Substring(0, fileindex);
            fileAddress += newName;

            File.Move(filepath, fileAddress);
        }

        string[] subdirectories = Directory.GetDirectories(source);
        foreach (string subdirectory in subdirectories)
            FileRenamer(subdirectory, search, replace);
    }

Use this if you want all directories recursively:

using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (String filePath in Directory.GetFiles(@"C:\folderName\", "*.*", SearchOption.AllDirectories))
            {             
                File.Move(filePath, filePath.Replace("abc_", ""));
            }
        }
    }
}

这个命令可以解决问题,使用renamer

$ renamer --find "abc_" *

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