在C#中递归复制目录时出现文件使用错误

时间:2012-07-12 12:45:17

标签: c# directory copy

我正在尝试使用以下函数将包含所有子目录的整个目录复制到同一驱动器上的另一个文件夹中:

    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.

我没有使用该文件,第三方软件告诉我没有进程锁定文件,因此我怀疑复制功能在某处绊倒。

任何人都可以阐明为什么会发生这种情况或建议一个能更好地完成工作的功能吗?

由于

2 个答案:

答案 0 :(得分:1)

您可能需要考虑锁定对文件的访问权限,它不应该过多地降低您的速度,并且应该避免同时尝试访问该文件。

private object lockObj = new object();

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

这可以解决您的问题。

答案 1 :(得分: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);  
            }  
        }