Tweak000
Tweak000

Reputation: 15

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

Upvotes: 0

Views: 4441

Answers (2)

Habib
Habib

Reputation: 223402

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

Upvotes: 3

Steve Danner
Steve Danner

Reputation: 22188

string path = "Some Directory";
string prefix = "Some Prefix";

foreach (var file in Directory.GetFiles(path, "*.pdf"))
{
    var newName = Path.Combine(Path.GetDirectoryName(file), prefix + Path.GetFileName(file));
    File.Move(file, newName);
}

Upvotes: 1

Related Questions