1.关于打印目录树
前几天写文档,要解释一个目录里大部分的子目录和文件的用途,于是顺手写了一个打印文件目录树的C#工具类,可以将生成的目录树打印到Console或是文本文件中。
2.工具类源码
打印目录树工具类:DocTreeHelper
需要手动加载命名空间:System.IO
class DocTreeHelper
{
/// <summary>
/// 输出目录结构树
/// </summary>
/// <param name="dirpath">被检查目录</param>
public static void PrintTree(string dirpath)
{
if (!Directory.Exists(dirpath))
{
throw new Exception("文件夹不存在");
}
PrintDirectory(dirpath, 0, "");
}
/// <summary>
/// 将目录结构树输出到指定文件
/// </summary>
/// <param name="dirpath">被检查目录</param>
/// <param name="outputpath">输出到的文件</param>
public static void PrintTree(string dirpath, string outputpath)
{
if (!Directory.Exists(dirpath))
{
throw new Exception("文件夹不存在");
}
//将输出流定向到文件 outputpath
StringWriter swOutput = new StringWriter();
Console.SetOut(swOutput);
PrintDirectory(dirpath, 0, "");
//将输出流输出到文件 outputpath
File.WriteAllText(outputpath, swOutput.ToString());
//将输出流重新定位回文件 outputpath
StreamWriter swConsole = new StreamWriter(
Console.OpenStandardOutput(), Console.OutputEncoding);
swConsole.AutoFlush = true;
Console.SetOut(swConsole);
}
/// <summary>
/// 打印目录结构
/// </summary>
/// <param name="dirpath">目录</param>
/// <param name="depth">深度</param>
/// <param name="prefix">前缀</param>
private static void PrintDirectory(string dirpath, int depth, string prefix)
{
DirectoryInfo dif = new DirectoryInfo(dirpath);
//打印当前目录
if (depth == 0)
{
Console.WriteLine(prefix + dif.Name);
}
else
{
Console.WriteLine(prefix.Substring(0, prefix.Length - 2) + "| ");
Console.WriteLine(prefix.Substring(0, prefix.Length - 2) + "|-" + dif.Name);
}
//打印目录下的目录信息
for (int counter = 0; counter < dif.GetDirectories().Length; counter++)
{
DirectoryInfo di = dif.GetDirectories()[counter];
if (counter != dif.GetDirectories().Length - 1 ||
dif.GetFiles().Length != 0)
{
PrintDirectory(di.FullName, depth + 1, prefix + "| ");
}
else
{
PrintDirectory(di.FullName, depth + 1, prefix + " ");
}
}
//打印目录下的文件信息
for (int counter = 0; counter < dif.GetFiles().Length; counter++)
{
FileInfo f = dif.GetFiles()[counter];
if (counter == 0)
{
Console.WriteLine(prefix + "|");
}
Console.WriteLine(prefix + "|-" + f.Name);
}
}
}
3.调用实例
在Main函数中输入下面的代码进行调用
class Program
{
static void Main(string[] args)
{
string dirpath = @"D:\MyPrograms\Program4Use\DocumentTree";
string outputpath = @"output.txt";
DocTreeHelper.PrintTree(dirpath);
DocTreeHelper.PrintTree(dirpath, outputpath);
Console.WriteLine("Output Finished");
Console.WriteLine("输出完毕");
Console.ReadLine();
}
}
4.运行效果
1)调用DocTreeHelper.PrintTree(dirpath)将目录dirpath的信息输出到控制台
2)调用DocTreeHelper.PrintTree(dirpath, outputpath)将目录dirpath的信息输出到文本文件outputpath
5.其他注意事项
1)在输出到文件的函数中,本文中的代码是先将Console的输出定位到一个流中,再在完成功能后将Console的输出定位回控制台来实现的。输出到控制台的流,编码方式应该采用Console.OutputEncoding,如果使用Encoding.ASCII,可以正确输出英文,但之后输出汉字会出现乱码。
2)不要在输出到文本文件的内容中使用字符'\b',BackSpace在文本文件中也是一个字符,它并不会将光标向前移动。
END