本文介绍了在C#中创建表示文件夹结构(包括子文件夹)的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何生成一个结构化给定文件夹的XML文件,以递归表示所有文件&
How can produce an XML file structuring a given folder to recursively represent all the files & subfolders within it?
推荐答案
那是一个很好的问题示例,可以使用递归算法轻松解决!
That's great example of problem, that can be easily solved using recursive algorithm!
伪代码:
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
C#和 DirectoryInfo
/ XDocument
/ XElement
这样的类:
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;
}
用法示例:
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>
这篇关于在C#中创建表示文件夹结构(包括子文件夹)的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!