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

如何提取指定目录下文件的文件名与子目录名并存入数组?

解决方案

你可以利用.NET自带的Path类或FileInfo类来处理路径,比手动用Substring和LastIndexOf更可靠,还能自动适配不同系统的路径分隔符。以下是两种实现方式:

方法一:使用Path类(字符串操作)

先定义根目录路径,然后遍历每个文件路径,拆分出文件名和对应子目录:

string rootDir = @"C:\Sharing";
string[] fileArray = Directory.GetFiles(rootDir, "*.*", SearchOption.AllDirectories);
List<string[]> resultList = new List<string[]>();

foreach (string filePath in fileArray)
{
    // 获取文件名
    string fileName = Path.GetFileName(filePath);
    // 获取文件所在的目录
    string fileDirectory = Path.GetDirectoryName(filePath);

    // 计算目录相对于根目录的部分
    string relativePath = fileDirectory.Substring(rootDir.Length).TrimStart(Path.DirectorySeparatorChar);

    if (string.IsNullOrEmpty(relativePath))
    {
        // 文件在根目录下,仅存入文件名
        resultList.Add(new string[] { fileName });
    }
    else
    {
        // 提取一级子目录名(适配多级目录场景,只取根目录下的直接子目录)
        int separatorIndex = relativePath.IndexOf(Path.DirectorySeparatorChar);
        string subDirName = separatorIndex == -1 ? relativePath : relativePath.Substring(0, separatorIndex);
        resultList.Add(new string[] { fileName, subDirName });
    }
}

方法二:使用FileInfo类(面向对象风格)

通过FileInfo可以更直观地获取文件的目录信息,代码更简洁:

string rootDir = @"C:\Sharing";
string[] fileArray = Directory.GetFiles(rootDir, "*.*", SearchOption.AllDirectories);
List<string[]> resultList = new List<string[]>();
DirectoryInfo rootDirectoryInfo = new DirectoryInfo(rootDir);

foreach (string filePath in fileArray)
{
    FileInfo fileInfo = new FileInfo(filePath);
    string fileName = fileInfo.Name;

    // 判断文件是否在根目录下
    if (fileInfo.Directory.FullName.Equals(rootDirectoryInfo.FullName, StringComparison.OrdinalIgnoreCase))
    {
        resultList.Add(new string[] { fileName });
    }
    else
    {
        // 直接获取文件所在的一级子目录名称
        string subDirName = fileInfo.Directory.Name;
        resultList.Add(new string[] { fileName, subDirName });
    }
}

说明

  • 两种方法都能完美匹配你给出的示例场景:
    • C:\Sharing\Jerry2022\wedding.jpg → ['wedding.jpg', 'Jerry2022']
    • C:\Sharing\snapshot.jpg → ['snapshot.jpg']
    • C:\Sharing\Newsletter\cover-june.webp → ['cover-june.webp', 'Newsletter']
  • 如果遇到更深层级的目录(比如C:\Sharing\Docs\2023\report.pdf),方法一会提取Docs作为子目录名,方法二会提取2023,可根据你的实际需求调整逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:45:37