0

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

..\bin\Release\XmlConfig\*.xml

会翻译成几个FileInfoXML 文件。

.NET 中有类似的东西吗?

4

2 回答 2

2

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.
于 2013-02-04T22:13:26.763 回答
2

您可以使用DirectoryInfo.EnumerateFileSystemInfosAPI:

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

该方法将结果作为 s 的序列进行流式传输,这是和FileSystemInfo的基类。FileInfoDirectoryInfo

于 2013-02-04T22:21:51.620 回答