如何解析含通配符*的路径并实现C#文件/文件夹删除方法
解析带通配符的文件/文件夹路径并删除的C#实现
核心思路
要解析带*通配符的路径(如C:\Owners*\App*\Temp*),需将路径按目录段拆分,逐层匹配系统中存在的目录/文件:
- 将输入路径转为绝对路径,拆分为多个目录/文件名段
- 从根目录开始,逐层处理每个段:
- 若当前段含通配符,枚举当前路径下所有符合匹配规则的子目录或文件
- 若当前段无通配符,直接拼接路径并验证是否存在
- 最终收集所有匹配的具体路径,再执行删除操作
实现代码
路径解析工具类
using System; using System.Collections.Generic; using System.IO; using System.Linq; public static class PathResolver { // 解析带通配符的路径,返回所有匹配的具体路径 public static IEnumerable<string> GetMatchingPaths(string wildcardPath) { var fullPath = Path.GetFullPath(wildcardPath); var segments = fullPath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var currentPaths = new List<string> { segments[0] }; // 起始根目录(如C:\) for (int i = 1; i < segments.Length; i++) { var nextPaths = new List<string>(); var currentSegment = segments[i]; if (currentSegment.Contains("*") || currentSegment.Contains("?")) { foreach (var basePath in currentPaths) { if (!Directory.Exists(basePath)) continue; // 最后一段可能是文件或文件夹,中间段仅匹配文件夹 if (i == segments.Length - 1) { nextPaths.AddRange(Directory.EnumerateFiles(basePath, currentSegment)); nextPaths.AddRange(Directory.EnumerateDirectories(basePath, currentSegment)); } else { nextPaths.AddRange(Directory.EnumerateDirectories(basePath, currentSegment)); } } } else { foreach (var basePath in currentPaths) { var combinedPath = Path.Combine(basePath, currentSegment); if (Directory.Exists(combinedPath) || File.Exists(combinedPath)) { nextPaths.Add(combinedPath); } } } currentPaths = nextPaths; if (!currentPaths.Any()) break; // 无匹配路径时提前终止 } return currentPaths; } }
删除操作工具类
public static class FileSystemDeleter { // 解析通配符路径并删除所有匹配的文件/文件夹 public static void DeleteWildcardPaths(string wildcardPath) { var matchingPaths = PathResolver.GetMatchingPaths(wildcardPath); foreach (var path in matchingPaths) { try { if (File.Exists(path)) { File.Delete(path); // 可替换为日志记录 Console.WriteLine($"已删除文件: {path}"); } else if (Directory.Exists(path)) { // recursive: true 会删除文件夹内所有内容,按需调整 Directory.Delete(path, recursive: true); Console.WriteLine($"已删除文件夹: {path}"); } } catch (IOException ex) { Console.WriteLine($"删除失败[{path}]: {ex.Message}"); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"权限不足[{path}]: {ex.Message}"); } } } }
使用示例
// 调用删除方法,传入带通配符的路径 FileSystemDeleter.DeleteWildcardPaths(@"C:\Owners*\App*\Temp*");
注意事项
- 支持Windows文件系统标准通配符:
*匹配任意长度字符,?匹配单个字符 - 删除文件夹时,
recursive: true参数会递归删除所有子目录和文件,需谨慎使用 - 异常处理可根据业务需求调整(如写入日志、重试逻辑等)
- 若路径最后一段为文件通配符(如
*.log),会匹配所有符合规则的文件;若为文件夹通配符,则匹配并删除对应文件夹
内容的提问来源于stack exchange,提问作者Sonal Sharma
相关产品推荐
相关产品推荐

