最终目标是拥有某种形式的数据结构,用于存储要存储在 txt 文件中的目录的层次结构。
到目前为止,我正在使用以下代码,并且正在努力组合目录、子目录和文件。
/// <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 );
}