是否有类似Powershell的';s目录

本文关键字:目录 Powershell 是否 | 更新日期: 2023-09-27 17:57:42

我正在.NET中寻找一个内置功能,用于查询具有相对路径和通配符的文件夹,类似于Powershell的dir命令(也称为ls)。据我记忆所及,Powershell返回一个DirectoryInfoFileInfo.NET对象的数组,这些对象稍后可以用于处理。示例输入:

..'bin'Release'XmlConfig'*.xml

将转换为几个FileInfo的XML文件。

在.NET中有类似的东西吗?

是否有类似Powershell的';s目录

System.IO.Directory是提供该功能的静态类。

例如,你的例子是:

using System.IO;
bool searchSubfolders = false;
foreach (var filePath in Directory.EnumerateFiles(@"..'bin'Release'XmlConfig",
                                                  "*.xml", searchSubfolders))
{
    var fileInfo = new FileInfo(filePath); //If you prefer
    //Do something with filePath
}

一个更复杂的例子是:(注意,这并没有经过非常彻底的测试,例如,用'结束字符串会导致它出错)

var searchPath = @"c:'appname'bla????'*.png";
//Get the first search character
var firstSearchIndex = searchPath.IndexOfAny(new[] {'?', '*'});
if (firstSearchIndex == -1) firstSearchIndex = searchPath.Length;
//Get the clean part of the path
var cleanEnd = searchPath.LastIndexOf('''', firstSearchIndex);
var cleanPath = searchPath.Substring(0, cleanEnd);
//Get the dirty parts of the path
var splitDirty = searchPath.Substring(cleanEnd + 1).Split('''');
//You now have an array of search parts, all but the last should be ran with Directory.EnumerateDirectories.
//The last with Directory.EnumerateFiles
//I will leave that as an exercise for the reader.

您可以使用DirectoryInfo.EnumerateFileSystemInfos API:

var searchDir = new DirectoryInfo("..''bin''Release''XmlConfig''");
foreach (var fileSystemInfo in searchDir.EnumerateFileSystemInfos("*.xml"))
{
    Console.WriteLine(fileSystemInfo);
}

该方法将结果流式传输为FileSystemInfos序列,这是FileInfoDirectoryInfo的基类。