开发者

Easiest way to check if file exists within a subfolder

开发者 https://www.devze.com 2023-04-13 09:50 出处:网络
I am going getting all the folders within a folder as follows: foreach (DirectoryInfo directory in root.GetDirectories())

I am going getting all the folders within a folder as follows:

foreach (DirectoryInfo directory in root.GetDirectories())

I now want to check all the files in each of those folder individualally for an XML file.If the XML file exists I want to do something.

What would be the best way to go about this开发者_开发知识库?

I know this is the basis:

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

        }

but that is not working?


Try this method if you want to actually do something with the XML file. If you are just checking to see if any xml file exists then I would go a different route:

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


The Directory.GetFiles method:

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


As an alternative you could use Directory.GetFiles with your search pattern and action upon the found files...

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   
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消