2017-05-13 3 views
1

나는 아래의 코드가 그 덮어 쓰지 않고 대상 디렉토리에 파일을 복사하지만, 유지하는 것입니다 위해 내가 찾고 있어요 무엇기존 파일을 덮어 쓰지 않고 파일을 복사하려면 어떻게합니까?

string[] dirs = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly); 
string[] files = Directory.GetFiles(dirs[0]); 

     foreach (string file in files) 
     { 
      string fname = file.Substring(dirs[0].Length + 1); 
      string dist = Path.Combine(dirs[1], fname); 
      File.Copy(file, dist, true); 
     } 

존재하는 경우 파일을 덮어 쓰기와 복사 다른 디렉토리에서 텍스트 파일을 두 파일. 예를 들어 Windows에서와 같이 "test"라는 파일을 여러 번 복사하면

test 
test - Copy 
test - Copy (2) 
test - Copy (3) 
text 
text- Copy 
text- Copy (2) 
text- Copy (3) 

도움이 될 것입니다.

답변

1
는 변경

당신의

File.Copy(file, dist, true); 

당신이

public static void Copy(string sourceFileName, string destFileName, bool overwrite) 

매개 변수
sourceFileName 유형 MSDN에보고 한 경우

File.Copy(file, dist, false); 

사람 : 시스템. String 복사 할 파일입니다.
destFileName 형식 : System.String 대상 파일의 이름입니다.
디렉터리 일 수 없습니다.
overwrite 형식 : System.Boolean 대상 파일을 덮어 쓸 수 있으면 true이고, 그렇지 않으면 false입니다. 그렇지 않으면 false입니다.

그리고 대상 파일 이름을 변경하고 성공할 때까지 복사하려고의 방법으로 예외 처리를 추가

당신은 위의 같은 코드를 사용하려고 할 수 있습니다 1 UPDATE. 이것은 내게 당신이 제공 한 링크보다 짧은 것 같습니다. 가능한 경우에 대해서는 테스트하지 않았지만 "tmp-copy.txt"및 "tmp-copy (1) .txt"가있는 동안 "tmp.txt"를 복사하는 것과 같은 간단한 경우에 대해 작동합니다.

UPDATE 2 미안 네 ALL 기타 사항 서보 -OFF 만 내가

 string sourcePath = @"c:\Users\Admin\Desktop\tmp\test1\"; 
     string destinationPath = @"c:\Users\Admin\Desktop\tmp\test2\"; 
     string[] files = Directory.GetFiles(sourcePath); 

     foreach (string file in files) 
     { 
      string fname = file.Substring(sourcePath.Length); 
      string dest = Path.Combine(destinationPath, fname); 
      if (File.Exists(dest)) 
      { 
       var existingFiles = Directory.GetFiles(destinationPath); 
       var fileNum = existingFiles.Count(x => x.Substring(destinationPath.Length).StartsWith(Path.GetFileNameWithoutExtension(fname))); 
       dest = Path.Combine(destinationPath, Path.GetFileNameWithoutExtension(dest) + " copy" + (fileNum > 1 ? " (" + (fileNum - 1) + ")" : "") + Path.GetExtension(dest)); 
       File.Copy(file, dest); 
      } 
      else 
      { 
       File.Copy(file, dest); 
      } 
     } 

동일한 대상 폴더에 같은 폴더의 복사본을 반복 한 결과를 수정 한 .Count보다 후 5 번되어 사용 작은 버그가 있었다 다음과 같습니다 : enter image description here

+0

하지만이 예외는'file already exists' !!! – FSm

+0

@ FSm yeah 죄송합니다. 추가 작업을 추가하는 것을 잊어 버렸습니다. –

+0

@FSm 어떻게 작성해야할지 상상하지 못했습니다. 코드 –

1
 string extention = ".txt"; 
     string originalFileName = string.Format("test{0}", extention); 
     string duplicateFileName = "test"; 
     string changedName = duplicateFileName; 

     int count = 1; 
     while (File.Exists(changedName + extention)) 
     { 
      changedName = string.Format("{0} - Copy ({1})", 
       duplicateFileName, count++); 
     } 
     File.Copy(originalFileName, changedName + extention);