Книга: 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);
Console.WriteLine(di.FullName);
PrintFoldersinCurrentDirectory(di, -1);
Console.ReadLine();
}
private static void PrintFoldersinCurrentDirectory(
DirectoryInfo directory, int level) {
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(" ");
Console.Write("| ");
//---display subdirectory name---
Console.WriteLine(subDir.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
- Creating Database Users in PostgreSQL
- Working with Files and Directories
- Creating CDs from the Command Line
- Creating and Deleting Device Objects
- Creating a Delegate
- Creating a Root Password and User Accounts
- Creating Users
- Creating CDs and DVDs with Fedora's Graphical Clients
- Creating DVDs from the Command Line
- Creating and Configuring Local Printers
- Creating the Print Queue
- Creating a Database in MySQL