如何防止递归复制文件和目录?

How to prevent recursive in copying files and dirs?

我在复制时遇到了问题 files/dirs。几乎一整天都在挣扎。 我必须从根目录文件及其带有文件和子目录的目录中复制。 事实上,我做了一些事情。但是,我每次运行在Whosebug error.

abstract class SystemOperations {
    public virtual void SearchFiles() { }
    public virtual void SearchDirectories() { }

    public abstract void CreateDirectory(string DIR);
    public abstract void CloneContent(string DIR);
    public abstract void CreateJSON(string DIR);

    public void ExecuteCopying(string DIR) {
        CreateDirectory(DIR);
        CloneContent(DIR);
        CreateJSON(DIR);
    }
}

class FileOperations : SystemOperations {
    DirectoryInfo _MainPath;
    public DirectoryInfo MainPath {
        get { return _MainPath; }
        set { _MainPath = value; }
    }

    public FileOperations(DirectoryInfo MainPath) {
        this.MainPath = MainPath;
    }

    #region Unnecessary for current task
    public override void SearchFiles() {
        string path = "";
        FileInfo[] files = MainPath.GetFiles();

        foreach (FileInfo file in files) {
            path = file.Name;
        }
    }

    public override void SearchDirectories() {
        string path = "";
        DirectoryInfo[] directories = MainPath.GetDirectories();

        foreach (DirectoryInfo directory in directories) {
            path = directory.Name;
        }
    }
    #endregion

    public override void CreateDirectory(string DIR) {
        string newFolder = Path.Combine(MainPath + "", DIR);
        Directory.CreateDirectory(newFolder);
    }

    public override void CloneContent(string DIR) {

        foreach (var directory in Directory.GetDirectories(MainPath + "")) {
            string dir = Path.GetFileName(directory);

            CloneContent(Path.Combine(MainPath + "", dir));
        }

        foreach (var file in Directory.GetFiles(MainPath + "")) {
            File.Copy(file, Path.Combine(MainPath + "", Path.GetFileName(file)), true);
        }
    }

    public override void CreateJSON(string DIR) {
        if (!Directory.Exists(DIR)) {
            var asd = new DirectoryInfo(DIR);
        }
    }
}

class Program {
    static void Main() {
        SystemOperations task = new FileOperations(new DirectoryInfo(@"D:\LAK"));
        task.ExecuteCopying("COPY");
    }
}

因此,CloneContent 函数必须复制每个 dir/subdirs 个文件。但它的递归函数和我上面写的,我 运行 错误。而且不知道如何解决这个问题。谢谢!

您尝试确定接下来需要搜索哪个目录的方式存在某种问题,MainPath 的使用在我看来是错误的。

就我个人而言,我也总是更喜欢有一个辅助停止条件来避免 WhosebugException,就像我在下面使用的 maxrunCount。

如果您想要递归目录查找,您应该将代码重写为

void Main()
{
    string MainPath = "D:\LAK";
    // unless your directory is actually named \LAK:) you should use either @"D:\LAK" or "d:\LAK"
    CloneContent(MainPath,1000);
}

public void CloneContent(string directoryToSearch, int maxrunCount)
{
    if(maxrunCount==0)
        return;
        
    System.Diagnostics.Debug.Print(directoryToSearch);
    string[] directories = null;
    try
    {
        directories = Directory.GetDirectories(directoryToSearch);
    }
    catch(UnauthorizedAccessException ex) {
        System.Diagnostics.Debug.Print($"No access to dir {directoryToSearch}");
        directories = new string[0];
    }
    
    // ensure you have access to the current directoryToSearch
    foreach (var directory in directories)
    {
        CloneContent(directory,--maxrunCount);
    }
    System.Diagnostics.Debug.Print($"cloning {directoryToSearch}");
    // .... do the actual cloning here, 
    // you will end up here when there are no more subdirectories on the current branch
}

要使递归方法起作用,它必须至少有一个“退出”条件 - 它完成工作并可以展开堆栈的时间点。在我们的例子中,当没有更多的目录或文件可以从源复制到目标时。

编写此方法的一种方式是接受一个源目录和一个目标目录,然后它可以为每个子目录递归调用自身:

public static void CloneContent(string sourceDir, string destDir)
{
    // If the source directory doesn't exist, return
    if (!Directory.Exists(sourceDir)) return;
    
    // Create destination if needed
    Directory.CreateDirectory(destDir);

    // Copy files from this directory to the new path
    foreach (string file in Directory.GetFiles(sourceDir))
    {
        File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)));
    }

    // Recursively call this method for each sub directory
    foreach (string subDir in Directory.GetDirectories(sourceDir))
    {
        string dirName = Path.GetFileName(subDir);
        string newSource = Path.Combine(sourceDir, dirName);
        string newDest = Path.Combine(destDir, dirName);

        CloneContent(newSource, newDest);
    }
}