|
发表于 2020-5-20 10:30:54
|
显示全部楼层
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- //获取当前程序所在的文件路径
- String path = Directory.GetCurrentDirectory();
- String path2 = path.Substring(0, 3); //取盘符
- StreamWriter sw = null;
- try
- {
- //创建输出流,将得到文件名子目录名保存到txt中
- sw = new StreamWriter(new FileStream("files.txt", FileMode.Append));
- sw.WriteLine("根目录:" + path2);
- getDirectory(sw, path2, 2);
- }
- catch (IOException e)
- {
- Console.WriteLine(e.Message);
- }
- finally
- {
- if (sw != null)
- {
- sw.Close();
- Console.WriteLine("完成");
- }
- }
- }
- /*
- * 获得指定路径下所有文件名
- * StreamWriter sw 文件写入流
- * string path 文件路径
- * int indent 输出时的缩进量
- */
- public static void getFileName(StreamWriter sw, string path, int indent)
- {
- DirectoryInfo root = new DirectoryInfo(path);
- foreach (FileInfo f in root.GetFiles())
- {
- for (int i = 0; i < indent; i++)
- {
- sw.Write(" ");
- }
- sw.WriteLine(f.Name);
- }
- }
- //获得指定路径下所有子目录名
- public static void getDirectory(StreamWriter sw, string path, int indent)
- {
- getFileName(sw, path, indent);
- DirectoryInfo root = new DirectoryInfo(path);
- foreach (DirectoryInfo d in root.GetDirectories())
- {
- for (int i = 0; i < indent; i++)
- {
- sw.Write(" ");
- }
- sw.WriteLine("文件夹:" + d.Name);
- getDirectory(sw, d.FullName, indent + 2);
- sw.WriteLine();
- }
- }
- }
- }
复制代码 |
|