我有一个定义文件路径的字符串:
string duplicateFilePath = D:\User\Documents\processed\duplicate_files\file1.jpg;
Run Code Online (Sandbox Code Playgroud)
我要将一个文件移动到这个位置,但有时候一个名字相同的文件都准备好了.在这种情况下,我想区分文件名.我有每个文件的crc值,所以我认为可能很好用于确保单个文件名.我可以创建:
string duplicateFilePathWithCrc = duplicateFilePath + "(" + crcValue + ")";
Run Code Online (Sandbox Code Playgroud)
但这给了:
D:\User\Documents\processed\duplicate_files\file1.jpg(crcvalue);
Run Code Online (Sandbox Code Playgroud)
我需要:
D:\User\Documents\processed\duplicate_files\file1(crcvalue).jpg;
Run Code Online (Sandbox Code Playgroud)
如何在文件扩展名之前将crcvalue放入字符串中,请记住文件路径中可能还有其他.文件扩展名有所不同?
Rot*_*tem 35
使用System.IO.Path类中的静态方法拆分文件名并在扩展名前添加后缀.
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));
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
结果:
D:\ User \ Documents \ processed \ duplicate_files \ file1(42).jpg