使用Linq Xml 来读取一个目录下所有的文件并保存为Xml文档
1 public static XElement ToXml(this DirectoryInfo Dir)
2 {
3 XElement Root = new XElement("Dir", new XAttribute("Name", Dir.Name),new XAttribute("文件数",Dir.GetFiles().Count()), from SubDir in Dir.GetDirectories() select ToXml(SubDir), from F in Dir.GetFiles() select new XElement("文件", new List<XElement>{new XElement("文件名", F.Name),new XElement("扩展名",F.Extension)}));
4 return Root;
5 }
6
2 {
3 XElement Root = new XElement("Dir", new XAttribute("Name", Dir.Name),new XAttribute("文件数",Dir.GetFiles().Count()), from SubDir in Dir.GetDirectories() select ToXml(SubDir), from F in Dir.GetFiles() select new XElement("文件", new List<XElement>{new XElement("文件名", F.Name),new XElement("扩展名",F.Extension)}));
4 return Root;
5 }
6
应用的代码
1 XDocument Doc=new XDocument();
2 DirectoryInfo Dir=new DirectoryInfo("E://");
3 Doc.Add(LinqEach.ToXml(Dir));
4 string Url = Server.MapPath("/");
5 if (!Directory.Exists(Url)) { Directory.CreateDirectory(Url); }
6 Doc.Save(Url + "AA.xml");
7
2 DirectoryInfo Dir=new DirectoryInfo("E://");
3 Doc.Add(LinqEach.ToXml(Dir));
4 string Url = Server.MapPath("/");
5 if (!Directory.Exists(Url)) { Directory.CreateDirectory(Url); }
6 Doc.Save(Url + "AA.xml");
7