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

假如想象 提交于 2019-12-11 10:43:16

问题


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


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/15096397/creating-xml-file-representing-folder-structure-including-subfolders-in-c-shar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!