Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use LINQ to traverse a specified directory and output to XML

Shulou Source: shulou.com Published: 2022-06-02 09:02:51 09月28日 Update

This article introduces the knowledge of "how to use LINQ to traverse a specified directory and output it to XML". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Problem: use LINQ to traverse a specified directory and output to XML.

The code is as follows:

Public static XElement ToXml (this DirectoryInfo dir) {XElement root = new XElement ("Dir", new XAttribute ("Name", dir.Name), from subDir in dir.GetDirectories () select DirToXml (subDir), from file in dir.GetFiles () select new XElement ("File", file.Name); return root;}

When using it, you can do this:

DirectoryInfo dir = new DirectoryInfo (path); XElement dirdirXml = dir.ToXml (); OK, done. As you can see, LINQ is very powerful. Since it is so powerful, why not go further? What should I do if I want to traverse the formatted files in the directory? For example, I want to find out all the mp3 in the directory, so I can write code like this.

Public static XElement ToXml (this DirectoryInfo dir, string searchPattern) {XElement root = new XElement ("Dir", new XAttribute ("Name", dir.Name), from subDir in dir.GetDirectories () select DirToXml (subDir), from file in dir.GetFiles (searchPattern) select new XElement ("File", file.Name)); return root;} / / DirectoryInfo dir = new DirectoryInfo (path); XElement dirdirXml = dir.DirToXml ("* .mp3")

It's easy to take it a step further. What if I'm looking for files in multiple formats? For example, to find out the picture files in the directory (jpg, bmp, gif … (Ok, no problem, it can be written like this:

Public static XElement ToXml (this DirectoryInfo dir, string [] searchPatterns) {XElement root = new XElement ("Dir", new XAttribute ("Name", dir.Name), from subDir in dir.GetDirectories () select DirToXml (subDir), from pattern in searchPattern from file in dir.GetFiles (pattern) select new XElement ("File", file.Name); return root;} can be used like this: DirectoryInfo dir = new DirectoryInfo (path) XElement dirdirXml = dir.DirToXml (new [] {"* .mp3", "* .txt"}); "how to use LINQ to traverse a specified directory and output it to XML" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Directory output I want file time powerful further code content more format for example knowledge problem practical successful next dilemma picture multiple Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Information macOS Huawei vpn