Search code examples
c#filerenaming

C# Replacing filenames containing "." with " " but removing the file extension


I am rename the files in a folder that contain a "." with a " ".
Expected result... Before: "I.am.testing.txt", After: "I am testing.txt"
Actual result... Before: "I.am.testing.txt", After: "I am testing txt"

The problem is that it also removes the "." for the file extension which is obviously a problem..

string folderPath = new DirectoryInfo(textBoxDir.Text).FullName;
DirectoryInfo d = new DirectoryInfo(folderPath);
FileInfo[] filesDot = d.GetFiles("*.*");

foreach (FileInfo fi in filesDot)
{
    File.Move(fi.FullName, Path.Combine(fi.Directory.ToString(), fi.Name.Replace(".", " ")));
}

Solution

  • You can just use Path.GetFileNameWithoutExtension to only get the name of the file, and then just append the original extension name to the end.

    File.Move(fi.FullName, Path.Combine(fi.Directory.ToString(), Path.GetFileNameWithoutExtension(fi.Name).Replace(".", " ") + fi.Extension));