You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#编写控制台程序读取目录并将文件夹列表存入数组?

无需手动分隔符提取路径中的文件夹与文件名方案

完全可以做到,用编程语言原生的路径处理API就能实现需求,既不用手动写\\分隔符,也不需要正则匹配,还能把文件夹列表存入数组。以下是两种主流语言的实现示例:

C# 实现

利用.NET自带的System.IO命名空间下的DirectoryInfo和Path类,自动解析路径结构:

using System;
using System.Collections.Generic;
using System.IO;

class PathParser
{
    static void Main()
    {
        string targetPath = @"C:\base\dirA\dirB\dirC\filename.txt";
        
        // 提取文件名
        string fileName = Path.GetFileName(targetPath);
        
        // 从文件所在目录开始向上遍历,收集目标文件夹
        DirectoryInfo currentDir = new DirectoryInfo(Path.GetDirectoryName(targetPath));
        List<string> folderList = new List<string>();
        
        // 遍历到"base"目录为止,收集dirA、dirB、dirC
        while (currentDir.Name != "base")
        {
            folderList.Insert(0, currentDir.Name);
            currentDir = currentDir.Parent;
        }
        
        // 转成数组(如果需要固定数组格式)
        string[] folderArray = folderList.ToArray();
        
        // 输出结果
        Console.WriteLine("文件夹列表(数组形式):");
        foreach (var folder in folderArray)
        {
            Console.WriteLine(folder);
        }
        Console.WriteLine("\n文件名:");
        Console.WriteLine(fileName);
    }
}

Python 实现

用Python3.4+自带的pathlib模块,面向对象的路径处理更简洁:

from pathlib import Path

target_path = Path(r"C:\base\dirA\dirB\dirC\filename.txt")

# 直接获取文件名
file_name = target_path.name

# 收集目标文件夹并存入数组
folder_array = []
current_dir = target_path.parent

# 遍历到"base"目录停止
while current_dir.name != "base":
    folder_array.insert(0, current_dir.name)
    current_dir = current_dir.parent

# 输出结果
print("文件夹列表(数组形式):")
for folder in folder_array:
    print(folder)
print("\n文件名:")
print(file_name)

核心优势

  • 完全依赖语言原生API处理路径,自动适配Windows/Linux不同的路径分隔符
  • 文件夹列表最终都存入了数组(C#的List<T>.ToArray()、Python的list本身就是数组结构)
  • 无需手动编写分隔符或正则匹配,避免了路径格式兼容问题

内容的提问来源于stack exchange,提问作者tt_time

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:20:22