📄 ex-21-02
字号:
// Example 21-02: Exploring files and subdirectories
namespace Programming_CSharp
{
using System;
using System.IO;
class Tester
{
public static void Main()
{
Tester t = new Tester();
// choose the initial subdirectory
string theDirectory = @"c:\WinNT";
// call the method to explore the directory,
// displaying its access date and all
// subdirectories
DirectoryInfo dir = new DirectoryInfo(theDirectory);
t.ExploreDirectory(dir);
// completed. print the statistics
Console.WriteLine(
"\n\n{0} files in {1} directories found.\n",
fileCounter,dirCounter);
}
// Set it running with a directoryInfo object
// for each directory it finds, it will call
// itself recursively
private void ExploreDirectory(DirectoryInfo dir)
{
indentLevel++; // push a directory level
// create indentation for subdirectories
for (int i = 0; i < indentLevel; i++)
Console.Write(" "); // two spaces per level
// print the directory and the time last accessed
Console.WriteLine("[{0}] {1} [{2}]\n",
indentLevel, dir.Name, dir.LastAccessTime);
// get all the files in the directory and
// print their name, last access time, and size
FileInfo[] filesInDir = dir.GetFiles();
foreach (FileInfo file in filesInDir)
{
// indent once extra to put files
// under their directory
for (int i = 0; i < indentLevel+1; i++)
Console.Write(" "); // two spaces per level
Console.WriteLine("{0} [{1}] Size: {2} bytes",
file.Name,
file.LastWriteTime,
file.Length);
fileCounter++;
}
// get all the directories in the current directory
// and call this method recursively on each
DirectoryInfo[] directories = dir.GetDirectories();
foreach (DirectoryInfo newDir in directories)
{
dirCounter++; // increment the counter
ExploreDirectory(newDir);
}
indentLevel--; // pop a directory level
}
// static member variables to keep track of totals
// and indentation level
static int dirCounter = 1;
static int indentLevel = -1; // so first push = 0
static int fileCounter = 0;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -