2013-03-26 186 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