: C# 2008 Programmer

Creating a FileExplorer

Creating a FileExplorer

Now that you have seen how to use the various classes to manipulate files and directories, let's put them to good use by building a simple file explorer that displays all the subdirectories and files within a specified directory.

The following program contains the PrintFoldersinCurrentDirectory() function, which recursively traverses a directory's subdirectories and prints out its contents:

class Program {
static string path = @"C:Program FilesMicrosoft Visual Studio 9.0VC#";
static void Main(string[] args) {
DirectoryInfo di = new DirectoryInfo(path);
PrintFoldersinCurrentDirectory(di, -1);
private static void PrintFoldersinCurrentDirectory(
DirectoryInfo directory, int level) {
//---print all the subdirectories in the current directory---
foreach (DirectoryInfo subDir in directory.GetDirectories()) {
for (int i = 0; i <= level * 3; i++)
Console.Write(" ");
//---display subdirectory name---
//---display all the files in the subdirectory---
FileInfo[] files = subDir.GetFiles();
foreach (FileInfo file in files) {
//---display the spaces---
for (int i = 0; i <= (level+1) * 3; i++) Console.Write(" ");
//---display filename---
Console.WriteLine("* " + file.Name);
//---explore its subdirectories recursively---
PrintFoldersinCurrentDirectory(subDir, level);

Figure 11-2 shows the output of the program.

Figure 11-2

: 1.274. /Cache: 3 / 1