0

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
  • You are getting hoodywha? Throw up some of the output that's wrong, because the code seems correct. Commented Jan 21, 2010 at 13:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.