Posts Tagged ‘xml’

LINQ: Generate File System Hierarchy in XML

March 26th, 2009 Comments off

I happen to come across the need to export file system hirachy into an XML form for further processing, and here is my LINQ statements that does the job. Please note the recursion usage in XDirectoryElement function. Last word you need to ensure you have permission to read the directories, which doesn’t worry me in my case.

Main Function:

private static XElement XDirectoryElement(String root, String filespec)
return /// Create "Directory" element with Path attribute
new XElement("Directory", new XAttribute("Path", root),
new XElement("Files",  /// Add "Files" sub-element
from file in Directory.GetFiles(root, filespec)orderby file
select new XElement("File", Path.GetFileName(file))),
new XElement("Subdirectories", /// Add "Subdirectories" sub-element
from dir in Directory.GetDirectories(root) orderby dir
select XDirectoryElement(dir, filespec)));  /// Do it recursively!

The usage of the function:

String root = @"C:\Program Files\Microsoft Games";
root = Path.Combine(root, @"");
XElement xde = XDirectoryElement(root, "*.*");
String filename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SubDir.xml");
Process.Start(filename);  /// Open explorer to view the file.

A trimmed down version of the Output:

< ?xml version="1.0" encoding="utf-8"?>
<directory Path="C:\Program Files\Microsoft Games">
  <files />
    <directory Path="C:\Program Files\Microsoft Games\Chess">
        <directory Path="C:\Program Files\Microsoft Games\Chess\en-US">
          <subdirectories />

Categories: Linq Tags: , ,