首页 > 解决方案 > GetFileSystemInfos() 用于任意路径(使用通配符)而不是某个 DirectoryInfo

问题描述

我需要获取与给定任意路径相对应的文件\foo\bar\*.txt目录列表,例如. dir本质上,与这条路径产生的结果相同。

理想情况下,它应该是一个数组,FileSystemInfo而不是扩展文件名/路径字符串。

从某个根目录开始时,解决方法很简单

a = new DirectoryInfo(root_path);
return a.GetFileSystemInfos(my_pattern);

但是这次我没有定义root_pathmy_pattern是任意的,可以是相对、绝对或 UNC 路径。

为简单起见,假设我不需要递归解析通配符,即paths\*\like*\this?.txt. 通配符只能出现在最后一部分(但模式仍然可以匹配文件或目录)。

我可以分成my_pattern“目录”和“文件”部分(使用IO.Path.GetDirectoryName()等,然后像上面一样对待它们。但这对于任务来说感觉过于复杂,因为我必须单独处理其中一个部分为空的情况。

如果我可以获得DirectoryInfo“计算机根目录”,甚至绝对路径也可以从中获得,那将很容易,但这似乎是不可能的。

感觉这应该是单行的,但我在.NET中找不到它......

标签: .netpath

解决方案


令人讨厌的是,这基本上就是 .NET Framework 中的所有内容。你可以按照你的建议做,例如

var directory = Path.GetDirectoryName(path);
var file = Path.GetFileName(path);

// Determine if the path is a file path with wildcards
if (!string.IsNullOrEmpty(directory) 
    &&  !string.IsNullOrEmpty(file) 
    && (file.Contains("*") || file.Contains("?")))
{
    foreach (var match in Directory.EnumerateFiles(directory, file))
    {
        DeleteFile(match);
    }
}
else
{
    // TODO handling of path without wildcards
}

另一种方法是使用不可移植的 Windows API FindFirstFileEx(等)函数。


推荐阅读