Insert string into a filepath string before the file extension C#

Use the static methods in the System.IO.Path class to split the filename and add a suffix before the extension.

string AddSuffix(string filename, string suffix)
{
    string fDir = Path.GetDirectoryName(filename);
    string fName = Path.GetFileNameWithoutExtension(filename);
    string fExt = Path.GetExtension(filename);
    return Path.Combine(fDir, String.Concat(fName, suffix, fExt));
}

string newFilename = AddSuffix(filename, String.Format("({0})", crcValue));

int value = 42;
var path = @"D:\User\Documents\processed\duplicate_files\file1.jpg";
var fileName = String.Format("{0}({1}){2}", 
         Path.GetFileNameWithoutExtension(path), value, Path.GetExtension(path));
var result = Path.Combine(Path.GetDirectoryName(path), fileName); 

Result:

D:\User\Documents\processed\duplicate_files\file1(42).jpg

Tags:

C#