public static void StoreAllFilesToXml(string directoryPath, string destinationXmlFilePath, XmlNode parentNode, XmlDocument xmlDoc)
{
bool isFirst = false;
if (parentNode == null)
{
isFirst = true;
xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
string rootFolder = "directory_root";
parentNode = xmlDoc.CreateElement(rootFolder);
XmlAttribute rootName = xmlDoc.CreateAttribute("name");
rootName.Value = directoryInfo.Name;
parentNode.Attributes.Append(rootName);
}
var rootDirectory = new DirectoryInfo(directoryPath);
foreach (var directory in rootDirectory.GetDirectories())
{
Console.WriteLine("Directory Name: {0}", directory.Name);
XmlNode folder = xmlDoc.CreateElement("folder");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = directory.Name;
folder.Attributes.Append(name);
parentNode.AppendChild(folder);
StoreAllFilesToXml(directory.FullName, @"C:\Users\nhuang\Desktop\a.xml", folder, xmlDoc);
}
foreach (var file in rootDirectory.GetFiles())
{
Console.WriteLine("parentNode"+parentNode.Name);
Console.WriteLine("File Name: {0}", file.Name);
XmlNode fileName = xmlDoc.CreateElement("fileName");
fileName.InnerText = file.Name;
parentNode.AppendChild(fileName);
}
if(isFirst)
{
xmlDoc.AppendChild(parentNode);
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(destinationXmlFilePath, Encoding.UTF8)
{
Formatting = Formatting.Indented,
IndentChar = '\t',
Indentation = 1
})
{
xmlDoc.Save(xmlTextWriter);
}
}
}
使用时
XmlNode temp = null;
XmlDocument xmlDoc = new XmlDocument();
StoreAllFilesToXml(@"C:\Users\nhuang\Documents\学习资料", @"C:\Users\nhuang\Desktop\a.xml", temp, xmlDoc);
ReadXmlFromFile(@"C:\Users\nhuang\Desktop\a.xml");
本文介绍了一种将文件系统信息转换并存储为XML文件的方法。该方法递归地遍历指定目录及其子目录,将每个目录及文件的信息转化为XML元素,并最终保存到目标XML文件中。文中提供了一个具体的C#实现示例。
292

被折叠的 条评论
为什么被折叠?



