.net - GetFileSystemInfos() 用于任意路径(使用通配符)而不是某个 DirectoryInfo
问题描述
我需要获取与给定任意路径相对应的文件和\foo\bar\*.txt
目录列表,例如. dir
本质上,与这条路径产生的结果相同。
理想情况下,它应该是一个数组,FileSystemInfo
而不是扩展文件名/路径字符串。
从某个根目录开始时,解决方法很简单
a = new DirectoryInfo(root_path);
return a.GetFileSystemInfos(my_pattern);
但是这次我没有定义root_path
;my_pattern
是任意的,可以是相对、绝对或 UNC 路径。
为简单起见,假设我不需要递归解析通配符,即paths\*\like*\this?.txt
. 通配符只能出现在最后一部分(但模式仍然可以匹配文件或目录)。
我可以分成my_pattern
“目录”和“文件”部分(使用IO.Path.GetDirectoryName()
等,然后像上面一样对待它们。但这对于任务来说感觉过于复杂,因为我必须单独处理其中一个部分为空的情况。
如果我可以获得DirectoryInfo
“计算机根目录”,甚至绝对路径也可以从中获得,那将很容易,但这似乎是不可能的。
感觉这应该是单行的,但我在.NET中找不到它......
解决方案
令人讨厌的是,这基本上就是 .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(等)函数。
推荐阅读
- c# - Xamarin 表单:为什么 Popupimage 显示 2 次?
- php - 如何通过 laravel 在 JSON 数据库字段中存储具有 NULL 值的键?
- nsis - 使用 Nullsoft 安装应用程序时,如何在基于 32/64 位 windows 操作系统的目标文件夹中显示路径
- c# - 从组合框中动态添加 .EndsWith()
- select - 在jq中使用select和reduce?
- python - pytest 中的并行测试
- ios - CNContactViewController 新联系人取消按钮闪烁
- python - Pyhaproxy 作业在“前端”定义中给出未指定主机和端口
- c# - 找不到 Azure Cosmos BulkExecuter 方法
- android - Crashlytics/Fabric 初始化回调未调用