Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 308
Steve W Avatar asked Jun 23 '14 13:06

Steve W


2 Answers

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));
like image 55
Rotem Avatar answered Sep 22 '22 14:09

Rotem


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

like image 36
Sergey Berezovskiy Avatar answered Sep 22 '22 14:09

Sergey Berezovskiy