2014-06-23 44 views
3

我有一個定義的文件的路徑的字符串:字符串插入文件擴展名C#前一個文件路徑字符串

string duplicateFilePath = D:\User\Documents\processed\duplicate_files\file1.jpg; 

我將文件移動到這個位置,但與相同的,有時一個文件名字已經準備好了。在這種情況下,我想區分文件名。我有每個文件的crc值可用,所以我認爲可能很好用來確保單個文件名。我可以創建:

string duplicateFilePathWithCrc = duplicateFilePath + "(" + crcValue + ")"; 

但是這給:

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

,我需要:

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

我怎樣才能把crcvalue到文件擴展名之前的字符串,銘記在文件路徑和文件擴展名中可能有其他的。

+0

嘗試使用此http://msdn.microsoft.com/en-us/library/system.io.path.getextension(v=vs.110)。 aspx –

回答

17

使用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)); 
1
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); 

結果:

d:\用戶\文件\處理\ duplicate_files \文件1(42).JPG

0

像這樣

string duplicateFilePath = @"D:\User\Documents\processed\duplicate_files\file1.jpg"; 
string crcValue = "ABCDEF"; 
string folder = Path.GetDirectoryName(duplicateFilePath); 
string filename = Path.GetFileNameWithoutExtension(duplicateFilePath); 
string extension = Path.GetExtension(duplicateFilePath); 

string newFilename = String.Format("{0}({1}){2}", filename, crcValue, extension); 
string path_with_crc = Path.Combine(folder,newFilename); 
0

嘗試使用Path類(它在System.IO命名空間):

string duplicateFilePathWithCrc = Path.Combine(
     Path.GetDirectoryName(duplicateFilePath), 
     string.Format(
      "{0}({1}){2}", 
      Path.GetFileNameWithoutExtension(duplicateFilePath), 
      crcValue, 
      Path.GetExtension(duplicateFilePath) 
     ) 
    ); 
+0

這將只顯示帶有CRC值的新文件名!不是完整的路徑! –

+0

@AppDeveloper:我最初的答案只是想展示如何在文件名中間添加CRC。我現在已經增強了包含文件完整路徑的答案。 –