/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Dirs.cs -- Uses the DirectoryInfo class to recursively show
// subdirectories.
//
// Compile this program with the following command line:
// C:>csc Dirs.cs
using System;
using System.IO;
namespace nsStreams
{
public class Dirs
{
static public void Main (string [] args)
{
string StartDir = "";
// Build the directory name from any arguments
if (args.Length > 0)
{
foreach (string str in args)
{
StartDir += str;
StartDir += " ";
}
// Strip any trailing spaces from the directory name
char [] trim = new char[1] {' '};
StartDir.TrimEnd (trim);
}
else
{
StartDir = ".";
}
DirectoryInfo d;
try
{
d = new DirectoryInfo (StartDir);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine ("Cannot open directory " + StartDir);
return;
}
DirectoryInfo [] dirs;
try
{
dirs = d.GetDirectories ();
}
catch (UnauthorizedAccessException)
{
Console.WriteLine ("Not authorized to access " + StartDir);
return;
}
catch (DirectoryNotFoundException)
{
Console.WriteLine ("Cannot open directory " + StartDir);
return;
}
foreach (DirectoryInfo dir in dirs)
{
try
{
ShowDirectories (dir, 0);
}
catch (UnauthorizedAccessException)
{
continue;
}
}
}
static public void ShowDirectories (DirectoryInfo d, int level)
{
int spaces = level;
while (spaces-- >= 0)
Console.Write (" ");
Console.WriteLine (d);
DirectoryInfo [] dirs = d.GetDirectories ();
if (dirs.Length > 0)
{
foreach (DirectoryInfo dir in dirs)
{
try
{
ShowDirectories (dir, level + 2);
}
catch (UnauthorizedAccessException)
{
continue;
}
}
}
}
}
}
|