在.NET中是否有类似于Powershell的目录?

时间:2013-02-04 22:09:51

标签: c# vb.net

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

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

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

.NET中有类似内容吗?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:2)

您可以使用DirectoryInfo.EnumerateFileSystemInfos API:

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

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