user3206687 user3206687 - 1 year ago 100
C# Question

using substring to rename multiple file names c#

i need to rename multiple csv file names. I want to remove everything after the "-" so example "File-1.csv" will become just "File.csv". Heres my code thats not working,

DirectoryInfo d = new DirectoryInfo(@"C:\folder");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
File.Move(f.FullName, f.FullName.ToString().Substring(0, f.LastIndexOf('-')));

Any help would be appreciated, Thanks !

Answer Source

Your current code doesn't compile because you are calling .LastIndexOf() on the FileInfo object when you should be calling it on FileInfo.FullName. Your substring also chops off the extension from the filename string, which I don't think you want. Here is a solution that preserves the extension:

foreach (FileInfo f in infos)
    // Get the extension string from the existing file
    var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 1);

    // Get the filename, excluding the '-' as well as the extension
    var filename = f.FullName.SubString(0, f.FullName.LastIndexOf('-'));

    // Concatenate the filename and extension and move the file
    File.Move(f.FullName, String.Format("{0}{1}", filename, extension));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download