views:

45

answers:

1

I am trying to index a drive to a xml file. My pitiful attempt is this:

        internal static void createIndex(String path, String driveLabel) 
        {

            XDocument w = new XDocument();
            w.Add(createStructure(path, new XElement("root")));
            w.Save(driveLabel +".xml");
        }

        internal static XElement createStructure(String path, XElement x)
        {
            try
            {
                String[] files = Directory.GetFiles(path);
                String[] folders = Directory.GetDirectories(path);

                foreach (String s in folders)
                {
                    x.Add("directory", createStructure(s, x));
                }

                foreach (String f in files)
                {
                    x.Add(new XElement("file", f));
                }      
            }
            catch (Exception e) { }

            return x;
        }

some output here - simple file structure - root has 2 mp3s and 1 folder containing the 2 files.

 <?xml version="1.0" encoding="utf-8"?>
  <root>
  <file>E:\.wd_tv\ph.db</file>
  <file>E:\.wd_tv\ph.db-journal</file>directory<root>
  <file>E:\.wd_tv\ph.db</file>
  <file>E:\.wd_tv\ph.db-journal</file>directory</root>
  <file>E:\180.mp3</file>
  <file>E:\181.mp3</file>
  </root>

I am getting some strangely intermixed tags there and I simply don't get it. Any help appreciated.

using od's loop structure it changes to that:

 <?xml version="1.0" encoding="utf-8"?>
 <root>directory<root>directory</root>
     <file>E:\180.mp3</file>
     <file>E:\181.mp3</file>
 </root>
+1  A: 

Try the following looping structure:

        foreach (String s in folders)
        {
            x.Add("directory", createStructure(s, x));
            foreach (String f in files)
            {
                x.Add(new XElement("file", f));
            } 
        }

This way you will display the files belonging to a directory immediatly after the directories in it.

Oded