2013-03-26 184 views
0

我想將文件複製到目錄並重命名爲特定格式。但是如果文件名已經存在,它應該在文件擴展名之前追加{1},{2}或{3}。在C#中複製文件時檢查重複的文件名

我的代碼重命名並複製了文件,並將其命名爲我想要的格式say filename.pdf,當它檢查重複時,它將其重命名爲filename1.pdf。但當它再次嘗試複製時,它給出了一個錯誤「文件已存在」,但我希望它已將其命名爲filename02.pdf。

請問有人能幫我一把。

這是我寫到目前爲止的代碼。

{ 
     string fileSource, filesToCopy, target, nextTarget; 

     string sourceDir = @"C:\HCP_PDFs";    

     string destinationDir = @"C:\RenamedHcpPdfs"; 

     DirectoryInfo di = new DirectoryInfo(destinationDir); 

     // create the directory if it dosnt exist 

     if (!Directory.Exists(destinationDir)) 
     { 
      Directory.CreateDirectory(destinationDir); 
     } 

     foreach (string myFiles in lstBoxFilenames.Items) 
     { 

      filesToCopy = myFiles; 
      fileSource = Path.Combine(sourceDir, filesToCopy);   

      //Extract only HCP Name by splitting , removing file Extension and removing HCP ID 
      string hcp = filesToCopy.Split('_')[0]; 
      string hcpCd = filesToCopy.Split('_')[1]; 
      string hcpID = filesToCopy.Split('_')[2]; 
      string hcpName = String.Format((filesToCopy.Split('_')[3]).Replace(".pdf", ""));   

      //combine the HCP ID, HCP name and date             
      target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + ".pdf"); 

      // if file exists in directory then rename and increment filename by 1 
      int i = +1 ; 

      nextTarget = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + i + ".pdf"); 

      if (File.Exists(target)) 
      { 
       File.Copy(fileSource, nextTarget); 
       break; 
      } 

      //if file does not exist, rename    
      else 
      { 
       File.Copy(fileSource, target); 
      }   
     }    
    } 

回答

0

試試這個:

string target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}.pdf"); 
while(File.Exists(target)) 
     { 
      i++; 
      target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + i + ".pdf"); 

     } 

File.Copy(fileSource, target); 
break; 
+0

非常感謝Pouki06,它解決了它。 – Richie 2013-03-27 11:39:47

+1

Thx,請點擊我的帖子作爲「回答已解決的帖子」給另一個人;)(在我的回答前面的支票) – Pouki 2013-03-27 12:41:27

+0

剛纔那樣做,當我能夠使用你的建議解決它時正在尋找它。 – Richie 2013-03-27 13:29:24

0

做這個

而(File.Exists(目標)){ 我++;}

,現在我宣佈你的目標路徑。

+0

我這樣做,並沒有工作?任何其他想法? – Richie 2013-03-27 10:51:56

+0

使用while循環遍歷,直到找不到文件與目標+ i.ToString(),然後將目標重命名爲目標+ i.ToString() – Chris 2014-10-29 20:34:54