[英]Copy the files from folders recursively with wildcard characters (folder path has wildcard characters)
美好的一天。
我必須將文件夾(包括子文件夾)中的所有文件復制到其他共享驅動器位置,以備份數據。 我面臨的挑戰是帶有通配符的文件夾路徑。
例如,
文件夾結構如下
D:/文件夾1 /文件夾11 /文件夾111
D:/ Folder2 / Folder222 / Folder222222
D:/ Folder3 / Folder333333 / Folder3333333
我正在尋找輸入格式應該為“ D:/ Folder?/ Folder * / Folder *”。 因此,它必須根據通配符模式進行循環。
你能幫我么。
問候,
錢德拉
您可以使用簡單的RegularExpression
實現此目的。 我創建了一個為您完成工作的示例。
RegEx
字符串非常簡單: [AZ]:\\\\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;
}
然后,此調用將返回與您的模式匹配的所有文件夾的列表:
getMatchingSubDir("D:\\", "Folder*");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.