我将获取文件夹中的所有文件夹,如下所示:
foreach (DirectoryInfo directory in root.GetDirectories())
我现在想要检查每个文件夹中的所有文件,以获取XML文件。如果XML文件存在,我想做点什么。
最好的方法是什么?
我知道这是基础:
if (File.Exists("*.xml"))
{
}
但这不起作用?
答案 0 :(得分:2)
如果您想要对XML文件执行某些操作,请尝试使用此方法。如果您只是检查是否存在任何xml文件,那么我将采用不同的路径:
foreach (DirectoryInfo directory in root.GetDirectories())
{
foreach(string file in Directory.GetFiles(directory.FullName, "*.xml"))
{
//if you get in here then do something with the file
//an "if" statement is not necessary.
}
}
答案 1 :(得分:0)
if (Directory.GetFiles(@"C:\","*.xml").Length > 0) {
// Do something
}
答案 2 :(得分:0)
作为替代方案,您可以使用Directory.GetFiles
将搜索模式和操作用于找到的文件...
var existing = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
//...
foreach(string found in existing) {
//TODO: Action upon the file etc..
}
答案 3 :(得分:0)
foreach (DirectoryInfo directory in root.GetDirectories())
{
// What you have here would call a static method on the File class that has no knowledge
// at all of your directory object, if you want to use this then give it a fully qualified path
// and ignore the directory calls altogether
//if (File.Exists("*.xml"))
FileInfo[] xmlFiles = directory.GetFiles("*.xml");
foreach (var file in xmlFiles)
{
// do whatever
}
}