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

Copy the files from folders recursively with wildcard characters (folder path has wildcard characters)

美好的一天。

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

例如,

文件夹结构如下

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);
        }
    }
}
IEnumerable<string> getMatchingSubDir(string dirPath, string pattern)
{
   List<string> matchingFolders = new List<string>();
   DirectoryInfo myDir = new DirectoryInfo(dirPath);
   foreach (var subDir in myDir.GetDirectories(pattern))
   {
       matchingFolders.AddRange(getMatchingSubDir(subDir.FullName, pattern));
   }
   return matchingFolders;
}

然后此调用将 return 为您列出与您的模式匹配的所有文件夹:

getMatchingSubDir("D:\", "Folder*");