Search code examples
c#directoryfilenamesrenameprefix

Add prefix to all file names in a folder with a certain extension using C#


I have 4 directories that host different files in them. I currently have a form that if a certain checkbox is checked, it is suppose to go to that directory, and find all the pdf's in that directory and add a prefix to them.

for example, say folder 1 has 5 pdf's in them. i want it to go through and add "some prefix" to the file name. Before: Filename After: Some Prefix Filename


Solution

    • Get all the files in the directory using Directory.GetFiles
    • For each file create a new file path using parent directory path, prefix string and file name
    • Use File.Move to rename the file.

    It should be like:

    var files = Directory.GetFiles(@"C:\yourFolder", "*.pdf");
    string prefix = "SomePrefix";
    foreach (var file in files)
    {
        string newFileName = Path.Combine(Path.GetDirectoryName(file), (prefix + Path.GetFileName(file)));
        File.Move(file, newFileName);
    }