I have a string that defines the path of a file:
string duplicateFilePath = D:\User\Documents\processed\duplicate_files\file1.jpg;
I am going to move a file to this location but sometimes a file with the identical name exists all ready. In this case I want to differentiate the filename. I have the crc value of each file available so I figured that may be good to use to ensure individual file names. I can create:
string duplicateFilePathWithCrc = duplicateFilePath + "(" + crcValue + ")";
But this gives:
D:\User\Documents\processed\duplicate_files\file1.jpg(crcvalue);
and I need:
D:\User\Documents\processed\duplicate_files\file1(crcvalue).jpg;
How can I put the crcvalue into the string before the file extension, bearing in mind there could be other .'s in the file path and file extensions vary?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With