[英]Get files from specifically structured sub-folders?
如何從特定結構化的文件夾/子文件夾系統中獲取*.xml
文件以執行某些操作。
例如:用戶提供的路徑(例如myPath )中的父文件夾的示例結構為
2017-36459-20124-301236\2017\36459\20124\301236\301236.xml
我不能使用string[] tarDir = Directory.GetDirectories(myPath, "foldernameinitial");
因為文件夾名稱是可變的。 有誰知道如何解決這個問題?
當我從您的評論中收集澄清信息時,這將使您獲得僅包含文件的所有子目錄,即最后一個子目錄
static IEnumerable<string> GetLastDirectory(string path) =>
Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
.Where(dir => Directory.GetDirectories(dir).Length == 0);
現在將其用作:
var MyDirectories = GetLastDirectory(@"D:\Softwares\Xtras"); //your path goes here
foreach (var subdir in MyDirectories)
{
var onlyXMLfiles = Directory.GetFiles(subdir, "*.xml");
foreach (var file in onlyXMLfiles)
{
//do your operation
}
}
坦率地說,我不知道regex,我在regex101上嘗試了這種模式匹配。 但是,正如您在下面的評論中所說,您還想匹配目錄結構的模式,您可以執行以下操作:
string pattern = @"\d{4}-\d{4,10}-\d{4,10}-\d{4,10}\\\d{4}\\\d{4,10}\\\d{4,10}\\\d{4,10}";
//Now you won't have to use "GetLastDirectory", instead use "Directory.GetDirectories"
var MyDirectories = Directory.GetDirectories("your path goes here");
foreach (var subdir in MyDirectories)
{
if ((Regex.Match(subdir, pattern) != Match.Empty))
{
var onlyXMLfiles = Directory.GetFiles(subdir, "*.xml");
foreach (var file in onlyXMLfiles)
{
//do your operations
}
}
}
可能的模式說明:
\ : match keyword, maybe!?<br>
- : hyphen as mentioned in the folder structure<br>
\d : match digits only<br>
\d{4} : match digits of length 4 and above<br>
\d{4,10} : match digits of length 4 and limit upto upto 10<br>
\\ : match \ as in the folder path<br>
var job_folders = Directory.EnumerateDirectories(textBox1.Text, "*", SearchOption.TopDirectoryOnly);
if (job_folders.ToArray().Length == 0)
{
MessageBox.Show("NO job folders are found...");
}
else
{
foreach (string job_folder in job_folders)
{
var target_xml_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(x => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "xml");
var target_meta_file = Directory.GetFiles(job_folder, "*.xml", SearchOption.AllDirectories).Where(x => Path.GetFileName(Path.GetDirectoryName(x)).ToLower() == "meta");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.