[英]Is there an analog to Powershell's dir in .NET?
I am looking for a built-in functionality in .NET to query folders with relative paths and wildcards, similar to Powershell's dir
command (also known as ls
). 我正在寻找.NET中的内置功能来查询带有相对路径和通配符的文件夹,类似于Powershell的
dir
命令(也称为ls
)。 As far as I remember, Powershell returns an array of DirectoryInfo
and FileInfo
.NET objects, which can later be used for processing. 据我所记得,Powershell返回一个
DirectoryInfo
和FileInfo
.NET对象的数组,这些对象以后可用于处理。 Example input: 输入示例:
..\bin\Release\XmlConfig\*.xml
would translate into several FileInfo
's of XML files. 将转换为几个XML文件的
FileInfo
。
Is there anything like that in .NET? .NET中有类似的东西吗?
System.IO.Directory
is the static class that provides that functionality. System.IO.Directory
是提供该功能的静态类。
For instance your example would be: 例如,您的示例将是:
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
}
A more complex example would be: (note this isn't really tested very thoroughly, for instance ending a string with \\
would cause it to error) 一个更复杂的示例将是:(请注意,这并未经过非常彻底的测试,例如,以
\\
结尾的字符串会导致错误)
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.
You can use DirectoryInfo.EnumerateFileSystemInfos
API: 您可以使用
DirectoryInfo.EnumerateFileSystemInfos
API:
var searchDir = new DirectoryInfo("..\\bin\\Release\\XmlConfig\\");
foreach (var fileSystemInfo in searchDir.EnumerateFileSystemInfos("*.xml"))
{
Console.WriteLine(fileSystemInfo);
}
The method will stream the results as a sequence of FileSystemInfo
s, which is the base class for FileInfo
and DirectoryInfo
. 该方法将结果流作为
FileSystemInfo
的序列传输,该序列是FileInfo
和DirectoryInfo
的基类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.