c# - 使用通配符递归地从文件夹复制文件(文件夹路径有通配符)

标签 c# .net windows winforms windows-applications

美好的一天。

我必须将文件夹(包括子文件夹)中的所有文件复制到其他共享驱动器位置以备份数据。我面临的挑战是带有通配符的文件夹路径。

例如,

文件夹结构如下

D:/Folder1/Folder11/Folder111

D:/Folder2/Folder222/Folder222222

D:/Folder3/Folder333333/Folder3333333

我正在寻找输入格式应该是“D:/Folder?/Folder*/Folder*”。所以它必须根据通配符模式循环。

你能帮帮我吗

问候,

钱德拉

最佳答案

您可以使用简单的 RegularExpression 实现这一点。我创建了一个示例来为您完成这项工作。

RegEx 字符串非常简单:[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[ 0-9]{3}

[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
-----         --------        --------        --------
Drive         1x digit        2x digit        3x digit

请参阅 regexr 处的示例.

编辑:

//using System.IO;

public void CopyMatching(string drive)
{
    try
    {
        var backuplocation = ""; //the path where you wanna copy your files to
        var regex = new Regex(@"[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}");
        var directories = new List<string>();
        foreach (var directory in Directory.EnumerateDirectories(drive))
        {
            if (regex.IsMatch(directory))
            {
                directories.Add(directory);
            }
        }
        foreach (var directory in directories)
        {
            DirectoryCopy(directory, backuplocation, true);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

DirectoryCopy:

public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
    // Get the subdirectories for the specified directory.
    DirectoryInfo dir = new DirectoryInfo(sourceDirName);

    if (!dir.Exists)
    {
        throw new DirectoryNotFoundException(
            "Source directory does not exist or could not be found: "
            + sourceDirName);
    }

    DirectoryInfo[] dirs = dir.GetDirectories();
    // If the destination directory doesn't exist, create it.
    if (!Directory.Exists(destDirName))
    {
        Directory.CreateDirectory(destDirName);
    }

    // Get the files in the directory and copy them to the new location.
    FileInfo[] files = dir.GetFiles();
    foreach (FileInfo file in files)
    {
        string temppath = Path.Combine(destDirName, file.Name);
        file.CopyTo(temppath, false);
    }

    // If copying subdirectories, copy them and their contents to new location.
    if (copySubDirs)
    {
        foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = Path.Combine(destDirName, subdir.Name);
            DirectoryCopy(subdir.FullName, temppath, copySubDirs);
        }
    }
}

关于c# - 使用通配符递归地从文件夹复制文件(文件夹路径有通配符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34353942/

相关文章:

c# - "large"滚动时数据集崩溃 Gridview。 Win32错误

c# - 在 SQL smo 中迭代所有表时如何仅识别基表?

c# - XMLSerializer 不序列化 DateTime

c# - 是否可以创建自定义 ASP.NET MVC 强类型 HTML Helper?

c++ - 每 X 毫秒运行一段时间

c# - 如果 Task.Wait 尚未运行,它是否会启动任务?

c# - 在不使用循环的情况下更新 C# 中的数据表?

c# - 可以同时从同一个流写入/读取吗?

java - Runtime.exec 以非管理员身份运行

windows - 如何在 Windows 10 上使 wsl2 从停止状态变为运行状态