Deepanjan Nag
Deepanjan Nag

Reputation: 921

Creating XML file representing folder structure (including subfolders) in C#

How can produce an XML file structuring a given folder to recursively represent all the files & subfolders within it?

Upvotes: 0

Views: 23822

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

That's great example of problem, that can be easily solved using recursive algorithm!

Pseudo-code:

function GetDirectoryXml(path)
    xml := "<dir name='" + path + "'>"

    dirInfo := GetDirectoryInfo(path)
    for each file in dirInfo.Files
        xml += "<file name='" + file.Name + "' />"
    end for

    for each subDir in dirInfo.Directories
        xml += GetDirectoryXml(subDir.Path)
    end for

    xml += "</dir>"

    return xml
end function

It can be done with C# and DirectoryInfo/XDocument/XElement classes like that:

public static XElement GetDirectoryXml(DirectoryInfo dir)
{
    var info = new XElement("dir",
                   new XAttribute("name", dir.Name));

    foreach (var file in dir.GetFiles())
        info.Add(new XElement("file",
                     new XAttribute("name", file.Name)));

    foreach (var subDir in dir.GetDirectories())
        info.Add(GetDirectoryXml(subDir));

    return info;
}

And example of usage:

static void Main(string[] args)
{
    string rootPath = Console.ReadLine();
    var dir = new DirectoryInfo(rootPath);

    var doc = new XDocument(GetDirectoryXml(dir));

    Console.WriteLine(doc.ToString());

    Console.Read();
}

Output for one of directories on my laptop:

<dir name="eBooks">
  <file name="Edulinq.pdf" />
  <file name="MCTS 70-516 Accessing Data with Microsoft NET Framework 4.pdf" />
  <dir name="Silverlight">
    <file name="Sams - Silverlight 4 Unleashed.pdf" />
    <file name="Silverlight 2 Unleashed.pdf" />
    <file name="WhatsNewInSilverlight4.pdf" />
  </dir>
  <dir name="Windows Phone">
    <file name="11180349_Building_Windows_Phone_Apps_-_A_Developers_Guide_v7_NoCover (1).pdf" />
    <file name="Programming Windows Phone 7.pdf" />
  </dir>
  <dir name="WPF">
    <file name="Building Enterprise Applications with WPF and the MVVM Pattern (pdf).pdf" />
    <file name="Prism4.pdf" />
    <file name="WPF Binding CheatSheet.pdf" />
  </dir>
</dir>

Upvotes: 10

the_lotus
the_lotus

Reputation: 12748

It's a bit hard to know what's the problem you are having.

You'll need to use DirectoryInfo.GetFiles and DirectoryInfo.GetDirectories to get the list of files and folder, loop with recursion. Then use the Xml.XmlDocument to write the xml document.

Upvotes: 1

Related Questions