Renaming files in folder 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_",""));
}

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.

Tags:

C#

File