简体   繁体   English

复制文件夹但忽略一些子文件夹

[英]Copy a folder but ignoring some sub-folders

SOLVED, thanks to Dave's answer. 已解决,感谢Dave的回答。

He showed me how to stop the async task, which answered my 2nd question. 他向我展示了如何停止async任务,这回答了我的第二个问题。

To filter unwanted folders I have changed the SkipDirectory(string) to check the directory's path (If you have better solution, I would love to hear it). 为了过滤不需要的文件夹,我更改了SkipDirectory(string)以检查目录的路径(如果您有更好的解决方案,我希望听到它)。 The function is written in the bottom. 该函数写在底部。

I was wondering if there is a way in C# to copy a folder, but with some filters. 我想知道C#中是否有一种复制文件夹的方法,但是带有一些过滤器。 ie Excluding some sub folders. 即不包括一些子文件夹。

And how can I do it without making the program stuck. 以及如何在不使程序卡住的情况下做到这一点。 The current code that I have found copies the folder and all it's sub folders but the program gets stuck for a second. 我发现的当前代码会复制该文件夹及其所有子文件夹,但该程序会卡住一秒钟。

Another code that I have found uses async method, and it solved the sudden pause's problem but I couldn't stop it in the middle (There must be an option to stop the task) 我发现的另一个代码使用async方法,它解决了突然暂停的问题,但是我无法在中间停止它(必须有一个选项来停止任务)

To sum up, I have 2 things I need: 综上所述,我需要做两件事:

1) Copy a folder, excluding some sub folders. 1)复制一个文件夹,不包括某些子文件夹。

2) Copy the folder without making the program get stuck 2)复制文件夹而不会使程序卡住

Here is the first code I used (without async ): 这是我使用的第一个代码(不带async ):

private void Copy(string sourcePath, string destinationPath)
{
    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*",
   SearchOption.AllDirectories))
    {
        if (SkipDirectory(dirPath))
        {
            continue;
        }
        Debug.Log(dirPath);
        Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
    }

    //Copy all the files & Replaces any files with the same name
    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",
        SearchOption.AllDirectories))
    {
        try
        {
            FileInfo file = new FileInfo(newPath);
            if (SkipDirectory(file.DirectoryName)) continue;    
            text += ("Copying " + newPath + "\n\n");
            File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
        }
        catch (System.Exception)
        {

        }
    }
}

And the async code: async代码:

private async System.Threading.Tasks.Task Copy(string startDirectory, string endDirectory)
{
    foreach (string dirPath in Directory.GetDirectories(startDirectory, "*", SearchOption.AllDirectories))
    {
        if (!SkipDirectory(dirPath))
        {
            Debug.Log("Creating directory " + dirPath);
            Directory.CreateDirectory(dirPath.Replace(startDirectory, endDirectory));
            foreach (string filename in Directory.EnumerateFiles(dirPath))
            {
                try
                {
                    using (FileStream SourceStream = File.Open(filename, FileMode.Open))
                    {
                        using (FileStream DestinationStream = File.Create(filename.Replace(startDirectory, endDirectory)))
                        {
                            text += ("Copying " + filename + "\n\n");
                            await SourceStream.CopyToAsync(DestinationStream);
                        }
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning($"Inner loop:\t{filename}\t{e.Message}");
                }
            }
        }
        else
        {
            Debug.Log("Skipping " + dirPath);
        }
    }

    foreach (string filename in Directory.EnumerateFiles(startDirectory))
    {
        try
        {
            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                using (FileStream DestinationStream = File.Create(endDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                {

                    await SourceStream.CopyToAsync(DestinationStream);
                }
            }
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"Outter loop:\t{filename}\t{e.Message}");
        }
    }
}

The SkipDirectory(string) function only returns true/false based on the folder name: SkipDirectory(string)函数仅根据文件夹名称返回true / false:

private bool SkipDirectory(string dirPath)
{
    dirPath = dirPath.ToLower();
    string[] namesToSkip = { "library", "temp", "obj", ".vs" };
    foreach (string nameToSkip in namesToSkip)
    {
        // I now check the path of the folder to see if it matches.
        string unwantedPath = $@"{projectPath}\{nameToSkip}".ToLower();
        if (dirPath.StartsWith(unwantedPath))
        {
            return true;
        }
    }
    return false;
}

So you can pass a CancellationToken to your method and use that for requesting cancellation 因此,您可以将CancellationToken传递给您的方法,并将其用于请求取消

here is your're code updated to be use a Cancellation token 这是您的代码已更新为可以使用取消令牌

private async Task Copy(string startDirectory, string endDirectory, CancellationToken ct)
{
    foreach (string dirPath in Directory.GetDirectories(startDirectory, "*", SearchOption.AllDirectories))
    {
        //Here we check if cancellation has been requesting if it has it will throw an exception (you can also check the IsCancellationRequested property and return) 
        ct.ThrowIfCancellationRequested();

        if (!SkipDirectory(dirPath))
        {
            Debug.Log("Creating directory " + dirPath);
            Directory.CreateDirectory(dirPath.Replace(startDirectory, endDirectory));
            foreach (string filename in Directory.EnumerateFiles(dirPath))
            {
                try
                {
                    using (FileStream SourceStream = File.Open(filename, FileMode.Open))
                    {
                        using (FileStream DestinationStream = File.Create(filename.Replace(startDirectory, endDirectory)))
                        {
                            await SourceStream.CopyToAsync(DestinationStream,81920, ct); //Pass cancellation token in to here and this can also handle cancellation
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning($"Inner loop:\t{filename}\t{e.Message}");
                }
            }
        }
        else
        {
            Debug.Log("Skipping " + dirPath);
        }
    }

    foreach (string filename in Directory.EnumerateFiles(startDirectory))
    {
        //Here we check if cancellation has been requesting if it has it will throw an exception (you can also check the IsCancellationRequested property and return) 
        ct.ThrowIfCancellationRequested();
        try
        {
            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                using (FileStream DestinationStream = File.Create(endDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                {

                    await SourceStream.CopyToAsync(DestinationStream,81920, ct); //Pass cancellation token in to here and this can also handle cancellation
                }
            }
        }
        catch(OperationCanceledException)
        {
            throw;
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"Outter loop:\t{filename}\t{e.Message}");
        }
    }
}

then the caller of you're code can create a new Cancellation token by doing the following 那么您的代码调用者可以通过执行以下操作来创建新的Cancellation令牌

var cts = new CancellationTokenSource(); //you can also pass a value for a timeout to this ctor var token = cts.Token;

You can then cancel by calling cts.Cancel() 然后可以通过调用cts.Cancel()取消

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 C# 中的文件夹和子文件夹中获取文件名 - Get file names from folder and sub-folders in C# 如何计算收件箱子文件夹,包括Outlook中子文件夹下的子文件夹等 - How to count inbox sub-folders including sub-folders under sub-folders and so on in Outlook 从 Dropbox 上的公共共享文件夹和子文件夹下载图像 - Downloading images from publicly shared folders and sub-folders on Dropbox 使用带有SharpSSH的SFTP下载文件夹和子文件夹 - Download folders and sub-folders using SFTP with SharpSSH 为C#Intellisense生成XML文件,为子文件夹损坏 - Generating XML file for C# Intellisense, broken for sub-folders NUnit测试用例生成:如何创建子文件夹(层次结构)? - NUnit testcase generation: how to create sub-folders (hierarchy)? 从特定结构的子文件夹中获取文件? - Get files from specifically structured sub-folders? 忽略特定子文件夹的 C# 编译警告? - Ignore C# compile warnings for specific sub-folders? 根据文件夹 C# Winforms 的内容检查和列出子文件夹 - Check and list sub-folders based on contents of folders C# Winforms 如何使用 EWS 托管 API 从文件夹和公共文件夹的子文件夹中获取所有项目 - How To Get all ITEMS from Folders and Sub-folders of PublicFolders Using EWS Managed API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM