0

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

    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.

我没有使用该文件,第三方软件告诉我没有进程正在锁定该文件,所以我怀疑复制功能在某处跳闸。

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

谢谢

4

2 回答 2

1

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

private object lockObj = new object();

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

这应该可以解决您的问题。

于 2012-07-12T13:43:33.970 回答
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);  
            }  
        }  
于 2012-07-12T14:18:45.703 回答