C#如何获取指定路径下的子文件夹名称(不含完整路径)
指定路径下一级子文件夹纯名称提取方案
所有方案最终返回的字符串数组仅包含子文件夹本身名称,不会携带父路径前缀,输出格式符合['car', 'bike', 'bus']的预期。
- Python 实现
import os parent_path = "c:/videos" sub_folders = [entry.name for entry in os.scandir(parent_path) if entry.is_dir()]
- Node.js 实现
const fs = require('fs'); const parentPath = "c:/videos"; const subFolders = fs.readdirSync(parentPath, { withFileTypes: true }) .filter(entry => entry.isDirectory()) .map(entry => entry.name);
- Java 实现
import java.io.File; import java.util.ArrayList; import java.util.List; public class SubFolderExtractor { public static List<String> getSubFolderNames(String parentPath) { List<String> result = new ArrayList<>(); File parent = new File(parentPath); File[] entries = parent.listFiles(); if (entries != null) { for (File entry : entries) { if (entry.isDirectory()) { result.add(entry.getName()); } } } return result; } }
- C# 实现
using System.Collections.Generic; using System.IO; public class FolderHelper { public static List<string> GetSubFolderNames(string parentPath) { List<string> result = new List<string>(); foreach (string dir in Directory.GetDirectories(parentPath)) { result.Add(Path.GetFileName(dir)); } return result; } }
核心逻辑通用:遍历父路径下的文件系统条目,筛选出目录类型条目后,直接读取条目的名称属性,即可避免拼接父级完整路径。
内容的提问来源于stack exchange,提问作者Savad
相关产品推荐
相关产品推荐

