Click here to Skip to main content
15,897,519 members
Articles / Programming Languages / C#

C# XML Directory Lister

Rate me:
Please Sign up or sign in to vote.
4.29/5 (8 votes)
1 Oct 2001 254.6K   6.6K   57  
Generates a directory list as XML
using System;
using System.IO;
using System.Xml;
using System.Data;

namespace GregHack.XMLStuff.Cs
{

   /// <summary>
   /// This class generates a list of files in a directory as XML.  It can
   /// return the XML as a string, a W3C DOM document, or a DataSet.  I
   /// wrote this code to learn about the XML capabilities of the framework
   /// work specifically with the DataSets.
   /// </summary>
   public class XMLDirectoryLister
   {
      private Boolean m_bUseDOMCalls;

      /// <summary>
      /// Constructor
      /// </summary>
      /// <param name="bUseDOMCalls">Use W3C DOM calls to build XML?</param>
      /// <returns>None</returns>
      public XMLDirectoryLister( Boolean bUseDOMCalls )
      {
         m_bUseDOMCalls = bUseDOMCalls;
      }
      
      /// <summary>
      /// This method generates a list of files in a directory as XML and
      /// returns the XML as a string.
      /// </summary>
      /// <param name="strDirectory">List files in this directory</param>
      /// <returns>A XML string with the directory file list</returns>
      public string
      getXMLString( string strDirectory )
      {
         string strXML = "";
      
         XmlDocument doc = getXML( strDirectory );
         if ( doc != null )
         {
		      StringWriter writer = new StringWriter();
            doc.Save( writer );
            strXML = writer.ToString();
         }

         doc = null;
         return strXML;
      }
       

      /// <summary>
      /// This method generates a list of files in a directory as XML and
      /// returns the XML as a DataSet.
      /// </summary>
      /// <param name="strDirectory">List files in this directory</param>
      /// <returns>A DataSet with the directory file list</returns>
      public DataSet
      getXMLDataset( string strDirectory )
      {
         DataSet ds = null;
      
         string strXML = getXMLString( strDirectory );
         XmlDataDocument datadoc = new XmlDataDocument();
         datadoc.DataSet.ReadXml( new StringReader(strXML) );

         ds =  datadoc.DataSet;    
          
         return ds;
      }
       

      /// <summary>
      /// This public method generates a list of files in a directory as XML and
      /// returns the XML as a W3C DOM document.
      /// </summary>
      /// <param name="strDirectory">List files in this directory</param>
      /// <returns>A W3C DOM docuemnt with the directory file list</returns>
      public XmlDocument
      getXMLDocument( string strDirectory )
      {
         return getXML( strDirectory );
      }
   
      private XmlDocument
      getXML( string strDirectory )
      {
         XmlDocument xmlDoc;
         if ( m_bUseDOMCalls )
            xmlDoc = getXMLUsingDOMCalls( strDirectory );
         else
            xmlDoc = getXMLUsingTextWriterClass( strDirectory );
         
         return xmlDoc;
      }

      /// <summary>
      /// This private method generates a list of files in a directory as XML and
      /// returns the XML as a W3C DOM document using the DOM calls.
      /// </summary>
      /// <param name="strDirectory">List files in this directory</param>
      /// <returns>A W3C DOM docuemnt with the directory file list</returns>
      private XmlDocument
      getXMLUsingDOMCalls( string strDirectory )
      {
         // Create the document.
         XmlDocument doc = new XmlDocument();

         // Insert the xml processing instruction and the root node
         XmlDeclaration dec = 
            doc.CreateXmlDeclaration("1.0", "", "yes");
         doc.PrependChild ( dec );

         // Add the root element
         XmlElement nodeElem = 
            doc.CreateElement( "dirlist" );
         doc.AppendChild( nodeElem );
         
         Boolean bFirst = true;

         // Process the directory list
         DirectoryInfo dir = new DirectoryInfo( strDirectory );
         foreach ( FileSystemInfo entry in dir.GetFileSystemInfos() ) 
         {
            if ( bFirst == true )
            {
               // If we haven't added any elements yet, go ahead and add a text element which
               // contains the full directory path.
               XmlElement root = doc.DocumentElement;

               String strFullName = entry.FullName;
               String strFileName = entry.Name;
         
               String strDir = strFullName.Substring( 0, strFullName.Length - strFileName.Length );
               root.SetAttribute ("dir", strDir );

               bFirst = false;
            }   
            
            // Add a new text node with a tag entry.  There will be one added per
            // item encountered in the directory.
            XmlElement elem = doc.CreateElement("entry");
            doc.DocumentElement.AppendChild(elem);
            
            // Write out the things we are interested in about this entry in the
            // directory.
            addTextElement( doc, elem, "name", entry.Name );
            addTextElement( doc, elem, "created", entry.CreationTime.ToString() );
            addTextElement( doc, elem, "lastaccess", entry.LastAccessTime.ToString() );
            addTextElement( doc, elem, "lastwrite", entry.LastWriteTime.ToString() );
            addTextElement( doc, elem, "isfile", ( (entry.Attributes & FileAttributes.Directory) > 0 ) ? "False" : "True" );
            addTextElement( doc, elem, "isdir", ( (entry.Attributes & FileAttributes.Directory) > 0 ) ? "True" : "False" );
            addTextElement( doc, elem, "readonly", ( (entry.Attributes & FileAttributes.ReadOnly) > 0 ) ? "True" : "False" );
         }
               
         return doc;
      } 
       

      /// <summary>
      /// This private method adds a text element to the XML document as the last
      /// child of the current element.
      /// </summary>
      /// <param name="doc">The XML document</param>
      /// <param name="nodeParent">Parent of the node we are adding</param>
      /// <param name="strTag">The tag of the element to add</param>
      /// <param name="strValue">The text value of the new element</param>
      private void
      addTextElement( XmlDocument doc, XmlElement nodeParent, string strTag, string strValue )
      {
          XmlElement nodeElem = doc.CreateElement( strTag );
          XmlText nodeText = doc.CreateTextNode( strValue );
          nodeParent.AppendChild( nodeElem );
          nodeElem.AppendChild( nodeText );
      } 


      /// <summary>
      /// This private method generates a list of files in a directory as XML and
      /// returns the XML as a W3C DOM document using the XmlTextWriter class.
      /// </summary>
      /// <param name="strDirectory">List files in this directory</param>
      /// <returns>A W3C DOM docuemnt with the directory file list</returns>
      private XmlDocument
      getXMLUsingTextWriterClass( string strDirectory )
      {
         StringWriter writerString = new StringWriter();
        
         XmlTextWriter writer = new XmlTextWriter( writerString );
         
         writer.WriteStartDocument(true);
         
         Boolean bFirst = true;
      
         // Process the directory list
         DirectoryInfo dir = new DirectoryInfo( strDirectory );
         foreach ( FileSystemInfo entry in dir.GetFileSystemInfos() ) 
         {
            
            if ( bFirst == true )
            {
               // If we haven't added any elements yet, go ahead and add a text element which
               // contains the full directory path.
               writer.WriteStartElement( "dirlist", "" );

               String strFullName = entry.FullName;
               String strFileName = entry.Name;
               String strDir = strFullName.Substring( 0, strFullName.Length - strFileName.Length );

               writer.WriteAttributeString( "dir", strDir );
               bFirst = false;
            }   

            // Add a new text node with a tag entry.  There will be one added per
            // item encountered in the directory.
            writer.WriteStartElement( "entry", "" );
         
            // Write out the things we are interested in about this entry in the
            // directory.
            writer.WriteElementString( "name", entry.Name );
            writer.WriteElementString( "created", entry.CreationTime.ToString() );
            writer.WriteElementString( "lastaccess", entry.LastAccessTime.ToString() );
            writer.WriteElementString( "lastwrite", entry.LastWriteTime.ToString() );
            writer.WriteElementString( "isfile", ( (entry.Attributes & FileAttributes.Directory) > 0 ) ? "False" : "True" );
            writer.WriteElementString( "isdir", ( (entry.Attributes & FileAttributes.Directory) > 0 ) ? "True" : "False" );
            writer.WriteElementString( "readonly", ( (entry.Attributes & FileAttributes.ReadOnly) > 0 ) ? "True" : "False" );
   
            writer.WriteEndElement();    // entry     
         }

         writer.WriteEndElement();       // dirlist
         writer.WriteEndDocument();

         string strXML = writerString.ToString();
         StringReader reader = new StringReader( strXML );
               
         XmlDocument doc = new XmlDocument();
         doc.Load( reader );
         
         return doc;
      } 
   }



}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions