检查子文件夹中是否存在文件的最简单方法

本文关键字:文件 最简单 方法 存在 是否 文件夹 检查 | 更新日期: 2023-09-27 18:11:08

我将获取文件夹中的所有文件夹,如下所示:

foreach (DirectoryInfo directory in root.GetDirectories())

我现在要检查每个文件夹中的所有文件,以查找XML文件。如果XML文件存在,我想做点什么。

做这件事最好的方法是什么?

我知道这是基础:

   if (File.Exists("*.xml"))
        {
        }

但这不起作用?

检查子文件夹中是否存在文件的最简单方法

如果您想对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.
    }
}
http://msdn.microsoft.com/en-us/library/wz42302f.aspx

目录。getfile方法:

if (Directory.GetFiles(@"C:'","*.xml").Length > 0) {
    // Do something
}

作为一种选择,您可以使用Directory.GetFiles与您的搜索模式和对找到的文件的操作…

var existing = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
//...
foreach(string found in existing) {
    //TODO: Action upon the file etc..
}
    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   
        }
    }