user3206687 user3206687 - 1 year ago 153
C# Question

Using substring to rename multiple file names using C#

I need to rename multiple CSV file names. I want to remove everything after the "-" so for example "File-1.csv" will become just "File.csv". Here's my code that's 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('-')));

I'm getting this error:

Error 2 'System.IO.FileInfo' does not contain a definition for 'LastIndexOf' and no extension method 'LastIndexOf' accepting a first argument of type 'System.IO.FileInfo' could be found (are you missing a using directive or an assembly reference?)

How can I fix this?

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