您的位置:首页 > 编程语言 > C#

c#:用xml递归存电脑指定路径的目录

2016-08-17 18:00 369 查看
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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#