C#生成目录树代码(DeepSeek版)



让DeepSeek写了一个Windows控制台程序,功能是将应用程序当前文件夹下的所有文件和文件夹生成一个目录树,保存在tree.txt文件中,项目使用.NET Framework 4.0 + C# 4.0:

using System;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static string treeFilePath;

    static void Main()
    {
        // 获取 exe 所在目录(去掉末尾的斜杠)
        string rootPath = AppDomain.CurrentDomain.BaseDirectory
                          .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

        // tree.txt 的完整路径(用于排除自身)
        treeFilePath = Path.Combine(rootPath, "tree.txt");

        // 使用 UTF-8 带 BOM 的编码覆盖写入
        using (var writer = new StreamWriter(treeFilePath, false, Encoding.UTF8))
        {
            WriteTree(rootPath, writer);
        }

        Console.WriteLine("\n树形结构已保存到: " + treeFilePath);
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
    }

    // 写入整棵目录树
    static void WriteTree(string rootPath, StreamWriter writer)
    {
        // 输出根节点(完整路径)
        string rootLine = rootPath;
        writer.WriteLine(rootLine);
        Console.WriteLine(rootLine);

        DirectoryInfo rootDir;
        try
        {
            rootDir = new DirectoryInfo(rootPath);
            // 获取根目录下的所有文件/文件夹(带异常保护)
            FileSystemInfo[] entries = GetFilteredSortedEntries(rootDir);
            for (int i = 0; i < entries.Length; i++)
            {
                bool isLast = (i == entries.Length - 1);
                WriteEntry(entries[i], "", isLast, writer);
            }
        }
        catch (UnauthorizedAccessException)
        {
            // 根目录通常不会无权限,这里保底不输出任何内容
        }
    }

    // 递归写入每一个条目(文件或文件夹)
    static void WriteEntry(FileSystemInfo entry, string indent, bool isLast, StreamWriter writer)
    {
        // 分支符号:最后一个用 └──,否则用 ├──
        string branch = isLast ? "└──" : "├──";
        string line = indent + branch + entry.Name;

        writer.WriteLine(line);
        Console.WriteLine(line);

        // 如果是文件夹,继续递归其子项
        if (entry is DirectoryInfo dir)
        {
            // 子项缩进:若当前是最后一项,后继用空格;否则保留竖线
            string childIndent = indent + (isLast ? "    " : "│   ");

            try
            {
                FileSystemInfo[] children = GetFilteredSortedEntries(dir);
                for (int i = 0; i < children.Length; i++)
                {
                    bool childIsLast = (i == children.Length - 1);
                    WriteEntry(children[i], childIndent, childIsLast, writer);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 无权限访问子文件夹 → 仅显示目录名,不再继续
            }
        }
    }

    // 获取指定目录下过滤并排序后的文件系统条目
    static FileSystemInfo[] GetFilteredSortedEntries(DirectoryInfo dir)
    {
        return dir.GetFileSystemInfos()
                  .Where(e =>
                  {
                      // 排除隐藏和系统属性
                      if ((e.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ||
                          (e.Attributes & FileAttributes.System) == FileAttributes.System)
                          return false;

                      // 排除 tree.txt 自身
                      if (string.Equals(e.FullName, treeFilePath, StringComparison.OrdinalIgnoreCase))
                          return false;

                      return true;
                  })
                  .OrderBy(e => e.Name, StringComparer.OrdinalIgnoreCase)  // 字母升序,不区分大小写
                  .ToArray();
    }
}

运行效果:

引用内容 引用内容
E:\WEB
├──AIAPP.md
├──index.html
├──package-lock.json
├──package.json
├──postcss.config.js
├──PROJECT_HANDOVER.md
├──src
│   ├──app.tsx
│   ├──components
│   │   ├──ImagePreview.tsx
│   │   └──Layout.tsx
│   ├──context
│   │   └──AuthContext.tsx
│   ├──index.css
│   ├──index.tsx
│   ├──lib
│   │   ├──captcha.ts
│   │   ├──image-compressor.ts
│   │   ├──supabase.ts
│   │   └──utils.ts
│   ├──pages
│   │   ├──AdminListPage.tsx
│   │   ├──CustomerListPage tbody.txt
│   │   ├──CustomerListPage.tsx
│   │   ├──CustomerListPage.tsx.bak
│   │   ├──DashboardPage.tsx
│   │   ├──InitPage.tsx
│   │   ├──ItemListPage.tsx
│   │   ├──LoginPage.tsx
│   │   └──PublicCustomerRepairsPage.tsx
│   └──types
│       └──database.ts
├──supabase
│   ├──migration
│   │   ├──001_create_customer_share_tokens.sql
│   │   ├──002_truncate_tables.sql
│   │   ├──003_fix_latitude_longitude_type.sql
│   │   ├──004_add_admin_login_security.sql
│   │   ├──005_add_administrator_to_repair_items.sql
│   │   ├──006_change_images_to_single_url.sql
│   │   ├──007_update_admin_roles_to_three_levels.sql
│   │   ├──add_admin_login_fields.sql
│   │   └──fix_last_login_ip_length.sql
│   └──tables
│       └──schema.sql
├──tailwind.config.js
├──tree.exe
├──tsconfig.json
├──tsconfig.node.json
└──vite.config.ts


上一篇: Edge浏览器控制台创建文件示例
下一篇: 这是最新一篇日志
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
最新日志:
评论: 0 | 引用: 0 | 查看次数: 28
发表评论
登录后再发表评论!