Search code examples
c#file-structure

Beginner - C# iteration through directory to produce a file list


The end goal is to have some form of a data structure that stores a hierarchal structure of a directory to be stored in a txt file.

I'm using the following code and so far, and I'm struggling with combining dirs, subdirs, and files.

/// <summary>
/// code based on http://msdn.microsoft.com/en-us/library/bb513869.aspx
/// </summary>
/// <param name="strFolder"></param>
public static void TraverseTree ( string strFolder )
{
  // Data structure to hold names of subfolders to be
  // examined for files.
  Stack<string> dirs = new Stack<string>( 20 );

  if ( !System.IO.Directory.Exists( strFolder ) )
  {
    throw new ArgumentException();
  }
  dirs.Push( strFolder );

  while ( dirs.Count > 0 )
  {
    string currentDir = dirs.Pop();
    string[] subDirs;
    try
    {
      subDirs = System.IO.Directory.GetDirectories( currentDir );
    }

    catch ( UnauthorizedAccessException e )
    {
      MessageBox.Show( "Error: " + e.Message );
      continue;
    }
    catch ( System.IO.DirectoryNotFoundException e )
    {
      MessageBox.Show( "Error: " +  e.Message );
      continue;
    }

    string[] files = null;
    try
    {
      files = System.IO.Directory.GetFiles( currentDir );
    }

    catch ( UnauthorizedAccessException e )
    {
      MessageBox.Show( "Error: " +  e.Message );
      continue;
    }

    catch ( System.IO.DirectoryNotFoundException e )
    {
      MessageBox.Show( "Error: " + e.Message );
      continue;
    }
    // Perform the required action on each file here.
    // Modify this block to perform your required task.
    /*
    foreach ( string file in files )
    {
      try
      {
        // Perform whatever action is required in your scenario.
        System.IO.FileInfo fi = new System.IO.FileInfo( file );
        Console.WriteLine( "{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime );
      }
      catch ( System.IO.FileNotFoundException e )
      {
        // If file was deleted by a separate application
        //  or thread since the call to TraverseTree()
        // then just continue.
        MessageBox.Show( "Error: " +  e.Message );
        continue;
      }
    } 
    */

    // Push the subdirectories onto the stack for traversal.
    // This could also be done before handing the files.
    foreach ( string str in subDirs )
      dirs.Push( str );

    foreach ( string str in files )
      MessageBox.Show( str );
  }

Solution

  • I got it working using code based on http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx

    // How much deep to scan. (of course you can also pass it to the method)
    const int HowDeepToScan=20;
    
    public static void ProcessDir ( string dirName, int recursionLvl, string strFileName)
    {
    
      string tabs = new String( '-', recursionLvl );
    
      if ( recursionLvl<=HowDeepToScan )
      {
        // Process the list of files found in the directory. 
        string [] fileEntries = Directory.GetFiles( dirName );
        TextWriter tw = new StreamWriter( strFileName, true );
        tw.WriteLine( tabs + "<a href=\" " +  System.IO.Path.GetFullPath( dirName ) + "\">" + System.IO.Path.GetFileName( dirName ) + "</a><br />" );
        foreach ( string fileName in fileEntries )
        {
          // do something with fileName
    
          tw.WriteLine( tabs + "<a href=\" " +  System.IO.Path.GetFullPath( fileName ) + "\">" + System.IO.Path.GetFileName( fileName ) + "</a><br />" );
    
        }
        tw.Close();
    
        // Recurse into subdirectories of this directory.
        string [] subdirEntries = Directory.GetDirectories( dirName );
        foreach ( string subdir in subdirEntries )
          // Do not iterate through reparse points
          if ( ( File.GetAttributes( subdir ) &
            FileAttributes.ReparsePoint ) !=
                FileAttributes.ReparsePoint )
    
            ProcessDir( subdir, recursionLvl+1, strFileName );
    
      }
    }
    

    output

    <a href=" C:\code">code</a><br />
    <a href=" C:\code\group.zip">FluentPath (1).zip</a><br />
    <a href=" C:\code\index.html">index.html</a><br />