Beginner - C# iteration through directory to produce a file list
Posted
by dassouki
on Stack Overflow
See other posts from Stack Overflow
or by dassouki
Published on 2010-04-28T19:05:35Z
Indexed on
2010/04/28
19:17 UTC
Read the original article
Hit count: 460
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 );
}
© Stack Overflow or respective owner