PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/HW_XML/Parsers/HW_XML_Parsers/09.TraverseDirectories/TraverseDirectories.cs

https://github.com/bankova/Databases
C# | 76 lines | 61 code | 6 blank | 9 comment | 0 complexity | 590ef6f7494e37e115d7bef1dccfc488 MD5 | raw file
  1. //Write a program to traverse given directory and write to a XML file its
  2. //contents together with all subdirectories and files. Use tags <file> and
  3. //<dir> with appropriate attributes. For the generation of the XML document
  4. //use the class XmlWriter.
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. using System.Xml.Linq;
  13. class TraverseDirectories
  14. {
  15. static void Main()
  16. {
  17. string folderLocation = "../../";
  18. string outpitFile = "../../directory.xml";
  19. DirectoryInfo dir = new DirectoryInfo(folderLocation);
  20. Encoding encoding = Encoding.GetEncoding("windows-1251");
  21. using (XmlTextWriter writer = new XmlTextWriter(outpitFile, encoding))
  22. {
  23. writer.Formatting = Formatting.Indented;
  24. writer.IndentChar = '\t';
  25. writer.Indentation = 1;
  26. writer.WriteStartDocument();
  27. writer.WriteStartElement("directories");
  28. CreateXML(writer, dir);
  29. writer.WriteEndDocument();
  30. }
  31. Console.WriteLine("Document {0} created.", outpitFile);
  32. Console.Read();
  33. }
  34. private static void CreateXML(XmlTextWriter writer, DirectoryInfo dir)
  35. {
  36. //get all the files first
  37. foreach (var file in dir.GetFiles())
  38. {
  39. string xml = new XElement("file", new XAttribute("name", file.Name)).ToString();
  40. XmlReader reader = XmlReader.Create(new StringReader(xml));
  41. writer.WriteNode(reader, true);
  42. }
  43. //get subdirectories
  44. var subdirectories = dir.GetDirectories().ToList().OrderBy(d => d.Name);
  45. foreach (var subDir in subdirectories)
  46. {
  47. CreateSubdirectoryXML(writer, subDir);
  48. }
  49. }
  50. private static void CreateSubdirectoryXML(XmlTextWriter writer, DirectoryInfo dir)
  51. {
  52. //get directories
  53. string xml = new XElement("dir", new XAttribute("name", dir.Name)).ToString();
  54. XmlReader reader = XmlReader.Create(new StringReader(xml));
  55. writer.WriteNode(reader, true);
  56. //get all the files first
  57. foreach (var file in dir.GetFiles())
  58. {
  59. xml = new XElement("file", new XAttribute("name", file.Name)).ToString();
  60. reader = XmlReader.Create(new StringReader(xml));
  61. writer.WriteNode(reader, true);
  62. }
  63. //get subdirectories
  64. var subdirectories = dir.GetDirectories().ToList().OrderBy(d => d.Name);
  65. foreach (var subDir in subdirectories)
  66. {
  67. CreateSubdirectoryXML(writer, subDir);
  68. }
  69. }
  70. }