如何从阵列中特定结构的文件夹/子文件夹系统中获取*.xml
个文件以执行某些操作。
例如:用户提供的路径中的父文件夹的示例结构(例如 myPath )是
2017-36459-20124-301236\2017\36459\20124\301236\301236.xml
由于文件夹名称可更改,我无法使用string[] tarDir = Directory.GetDirectories(myPath, "foldernameinitial");
之类的内容。
有谁知道如何解决这个问题?
答案 0 :(得分:1)
当我从您的评论中收集澄清时,这将获得所有子目录,其中只包含文件,即最后一个子目录
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
}
}
坦率地说,我不知道正则表达式,我在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>
答案 1 :(得分:0)
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");
}
}