Click here to Skip to main content
5,787,682 members and growing! (17,956 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » File System     Intermediate

XML Directory Tree Generator

By Erhan Hosca

Describes a directory tree documenter that outputs XML.
C#Windows, .NET, .NET 1.0, .NET 1.1, Win2K, WinXP, Win2003VS.NET2003, Visual Studio, Dev

Posted: 17 Sep 2003
Updated: 17 Sep 2003
Views: 56,248
Bookmarked: 24 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
8 votes for this Article.
Popularity: 2.71 Rating: 3.00 out of 5
3 votes, 37.5%
1
0 votes, 0.0%
2
1 vote, 12.5%
3
3 votes, 37.5%
4
1 vote, 12.5%
5

Introduction

This code snippet recursively enumerates all the folders and files under a given starting folder and generates an XML document as an output, that represents the same hierarchy as of the traversed directories. The resulting XML document can then be transformed with a simple XSLT transformation to generate the desired output. The main reason for writing this was to display the contents of a given directory on a website, without having to enable directory browsing on the server. I wanted to be able to define certain filter criteria to control the output generated, so it was important to capture as much information pertaining to the folders and files as possible.

Using the code

The code is implemented as FileSystemInfoLister class. The main entry point is the GetFileSystemInfoList() method that returns an XML document. The AddElements() method is called recursively until the entire path is traversed.

using System;
using System.Xml;
using System.IO;


namespace Hosca.FileSystemInfoLister {

    public class FileSystemInfoLister {

        XmlDocument xmlDoc;

        public FileSystemInfoLister() {
            xmlDoc = new XmlDocument();
        }

        public XmlDocument GetFileSystemInfoList(string StartFolder) {

            try{
                XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", 
                                                                "", "yes");
                xmlDoc.PrependChild ( xmlDec );
                XmlElement nodeElem =  XmlElement("folder",
                         new DirectoryInfo(StartFolder).Name); 
                xmlDoc.AppendChild(AddElements(nodeElem,StartFolder));
            }
            catch(Exception ex) {
                xmlDoc.AppendChild(XmlElement("error",ex.Message));
                return xmlDoc;
            }
            return xmlDoc;
        }


        private XmlElement AddElements(XmlElement startNode, 
                                               string Folder){
            try{
                DirectoryInfo dir = new DirectoryInfo(Folder);
                DirectoryInfo[] subDirs = dir.GetDirectories() ;
                FileInfo[] files = dir.GetFiles();
                foreach(FileInfo fi in files){
                  XmlElement fileElem = XmlElement("file",fi.Name);
                  fileElem.Attributes.Append(XmlAttribute("Extension", 
                                                           fi.Extension));
                  fileElem.Attributes.Append(XmlAttribute("Hidden", 
                   ((fi.Attributes & FileAttributes.Hidden) != 0) 
                                                       ? "Y":"N"));
                  fileElem.Attributes.Append(XmlAttribute("Archive", 
                   ((fi.Attributes & FileAttributes.Archive ) != 0) 
                                                       ? "Y":"N"));
                  fileElem.Attributes.Append(XmlAttribute("System", 
                   ((fi.Attributes & FileAttributes.System ) != 0) 
                                                       ? "Y":"N"));
                  fileElem.Attributes.Append(XmlAttribute("ReadOnly", 
                   ((fi.Attributes & FileAttributes.ReadOnly ) != 0) 
                                                        ? "Y":"N"));
                  startNode.AppendChild(fileElem);
                }
                foreach (DirectoryInfo sd in subDirs) {
                  XmlElement folderElem = XmlElement("folder",sd.Name);
                  folderElem.Attributes.Append(XmlAttribute("Hidden", 
                    ((sd.Attributes & FileAttributes.Hidden) != 0) 
                                                       ? "Y":"N"));
                  folderElem.Attributes.Append(XmlAttribute("System", 
                    ((sd.Attributes & FileAttributes.System  ) != 0) 
                                                       ? "Y":"N"));
                  folderElem.Attributes.Append(XmlAttribute("ReadOnly",
                    ((sd.Attributes & FileAttributes.ReadOnly ) != 0)
                                                       ? "Y":"N"));
                  startNode.AppendChild(AddElements(folderElem,
                                                     sd.FullName));
                }
                return startNode;
            }
            catch(Exception ex) {
                return XmlElement("error",ex.Message);
            }
        }
        private XmlAttribute XmlAttribute(string attributeName, 
                                          string attributeValue){
            XmlAttribute xmlAttrib = 
                xmlDoc.CreateAttribute(attributeName);
            xmlAttrib.Value = FilterXMLString(attributeValue);
            return xmlAttrib;
        }
        private XmlElement XmlElement(string elementName, 
                                       string elementValue){
            XmlElement xmlElement = xmlDoc.CreateElement(elementName);
            xmlElement.Attributes.Append(XmlAttribute("name", 
                                      FilterXMLString(elementValue)));
            return xmlElement;
        }
        private string FilterXMLString(string inputString){
            string returnString = inputString;
            if (inputString.IndexOf("&") > 0){
                returnString = inputString.Replace("&","&");
            }
            if (inputString.IndexOf("'") > 0){
                returnString = inputString.Replace("'","'");
            }
            return returnString;
        }    
    }
}

Points of interest

The only minor point of interest is that there are 2 characters that are allowable in file names but not in XML documents. In fact there are 5 characters that are not allowed in XML documents. They are :

< < less than
> > greater than
& & ampersand
&apos; ' apostrophe
" " quotation mark

Fortunately for us, Windows takes care of 3 of them. However the ampersand and the apostrophe which are legal to use in file names will have to be handled manually. The FilterXMLString method takes care of the details.

History

  • Sept 18 2003 - Initial version (1.0.0)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Erhan Hosca



Occupation: Web Developer
Location: United States United States

Other popular Files and Folders articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
GeneralMy vote of 1membermovhlps6:20 29 Nov '08  
QuestionEditing XML filememberKrishnakumar Bhagwat22:17 21 Aug '06  
GeneralSmall bug in FilterXMLStringmemberRichard Poole7:15 12 May '04  
GeneralRe: Small bug in FilterXMLStringmemberErhan Hosca8:15 12 May '04  
GeneralRe: Small bug in FilterXMLStringmemberdjarn23:34 29 Oct '04  
GeneralHandling AmpersandsmemberDonald Xie16:11 11 Jan '04  
GeneralRe: Handling AmpersandsmemberErhan Hosca4:29 12 Jan '04  
GeneralVery cool - I want more!sussShem Stimpy4:32 25 Sep '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Sep 2003
Editor: Smitha Vijayan
Copyright 2003 by Erhan Hosca
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project