2012-07-12 54 views
0

我試圖複製,包括所有子目錄到另一個文件夾使用下面的功能相同的驅動器上的整個目錄:文件在使用錯誤的C#遞歸拷貝目錄時

private static void CopyAll(DirectoryInfo source, DirectoryInfo target) 
    { 
     // Check if the target directory exists, if not, create it. 
     if (Directory.Exists(target.FullName) == false) 
     { 
      Directory.CreateDirectory(target.FullName); 
     } 

     // Copy each file into it’s new directory. 
     foreach (FileInfo fi in source.GetFiles()) 
     { 
      Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); 
      fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); 
     } 

     // Copy each subdirectory using recursion. 
     foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) 
     { 
      DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); 
      CopyAll(diSourceSubDir, nextTargetSubDir); 
     } 
    } 

調用具有:

public void copyTemplate(string templatepath, string destpath) 
    { 
     DirectoryInfo s = new DirectoryInfo(@"C:\temp\templates\template1"); 
     DirectoryInfo t = new DirectoryInfo(@"C:\temp\www_temp\gtest"); 

     CopyAll(s, t); 
    } 

它產生錯誤:

The process cannot access the file 'C:\temp\templates\template1\New folder\alf.txt' because it is being used by another process. 

的文件不在使用由我並且第三方軟件告訴我沒有進程正在鎖定文件,所以我懷疑複製功能正在某處跳動。

任何人都可以闡明爲什麼這可能會發生或提出一個功能,可以更好地完成這項工作嗎?

感謝

回答

0

用以下解決問題替換CopyAll()函數。

public static void CopyFolder(string sourceFolder, string destFolder) 
     { 
      if (!Directory.Exists(destFolder)) 
       Directory.CreateDirectory(destFolder); 
      string[] files = Directory.GetFiles(sourceFolder); 
      foreach (string file in files) 
      { 
       string name = Path.GetFileName(file); 
       string dest = Path.Combine(destFolder, name); 
       File.Copy(file, dest); 
      } 
      string[] folders = Directory.GetDirectories(sourceFolder); 
      foreach (string folder in folders) 
      { 
       string name = Path.GetFileName(folder); 
       string dest = Path.Combine(destFolder, name); 
       CopyFolder(folder, dest); 
      } 
     } 
1

你可能要考慮鎖定對文件的訪問,它不應該降低你的速度太多,應避免任何試圖在同一時間訪問該文件。

private object lockObj = new object(); 

lock(lockObj) 
{ 
//Code to access file 
} 

這應該可以解決您的問題。