2013-02-04 35 views
0

我正在尋找.NET中的內置功能來查詢具有相對路徑和通配符的文件夾,類似於Powershell的dir命令(也稱爲ls)。據我記憶,Powershell返回一個數組DirectoryInfoFileInfo .NET對象,稍後可用於處理。示例輸入:在.NET中是否有類似Powershell的目錄?

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

會翻譯成幾個FileInfo的XML文件。

在.NET中是否有類似的東西?

+0

Um。 'FileInfo'和'DirectoryInfo'?你需要什麼模擬器?那些應該做的。 – Oded

+0

@Oded:我正在尋找正確的函數來返回基於過濾器的FileInfo的數組/列表/枚舉。 – Neolisk

+0

你爲什麼不看'FileInfo'或'DirectoryInfo' MSDN頁面呢?第一停靠港,你會找到你的答案。 – Oded

回答

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. 
+0

如果我無法將路徑分隔到文件夾+擴展名過濾器中,該怎麼辦?例如'.. \ bin \ Release \ XmlCon ??? \ *。xml'? – Neolisk

+0

@Neilisk:我添加了最後一個參數來告訴你如何使用它。 – Guvante

+0

您是否閱讀過我的評論?你的例子假設會有一個根路徑,我將只在下面的文件掩碼進行過濾。如果還有文件夾遮罩呢? Powershell的目錄處理這種情況就好了。 – Neolisk

2

您可以使用DirectoryInfo.EnumerateFileSystemInfos API:

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

該方法將流式處理結果作爲FileSystemInfo的一個序列,這是FileInfoDirectoryInfo的基類。

+0

VS抱怨'EnumerateFileSystemInfos'在當前上下文中不存在。如果我刪除它並留下兩個參數,它說'非靜態成員需要一個對象引用。 – Neolisk

+0

錯字。我已經更新了您的特定用法的示例。 –

+0

感謝您的更新。像'.. \ bin \ Release \ XmlCon ??? \ *。xml'這樣的情況怎麼辦?看起來像'EnumerateFileSystemInfos'不能處理它們。 – Neolisk

相關問題