簡體   English   中英

如何獲取目錄和子目錄的列表C#WPF

[英]How to get a list of directories and sub directories C# WPF

您將如何從根目錄中獲得所有子目錄及其子目錄(直到沒有子目錄)的列表。

我當前的代碼使用FolderBrowserDialog(WPF沒有它,所以我必須從winforms中獲取它),然后從那里嘗試遍歷目錄。 到目前為止,我只能使它橫向於1級深,例如

如果音樂目錄設置為

\rock\metallica\ride the lightning
\rock\aerosmith\
\rock\something\

而用戶選擇\\ rock \\,則只會從aerosmith,某物和metallica而不是metallica的子目錄中獲取文件,而是繞行閃電。

private void btnAddTestFile_Click(object sender, RoutedEventArgs e)
{
    string[] files;
    FolderBrowserDialog dlg = new FolderBrowserDialog();

    DialogResult result = dlg.ShowDialog();
    if (result.ToString() == "OK")
    {
        InitializePropertyValues();


        files = System.IO.Directory.GetFiles(dlg.SelectedPath, "*.mp3");
        foreach (string file in files)
        {
            lstvTrackList.Items.Add(new TrackList{ ID = lstvTrackList.Items.Count.ToString(), TrackName = Regex.Match(file, @".*\\(.*).mp3").Groups[1].Value, TrackPath = file });
        }

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dlg.SelectedPath);
        foreach (System.IO.DirectoryInfo d in di.GetDirectories())
        {
            files = System.IO.Directory.GetFiles(d.FullName, "*.mp3");
            foreach (string file in files)
            {
                lstvTrackList.Items.Add(new TrackList{ ID = lstvTrackList.Items.Count.ToString(), TrackName = Regex.Match(file, @".*\\(.*).mp3").Groups[1].Value, TrackPath = file });
            }
        }
    }
}

基本上,我試圖做的是首先從根目錄中添加所有松散文件,然后在根目錄中獲取目錄列表並添加這些文件。

如果我知道如何從根目錄開始爬網所有子目錄,我想我可以弄清楚,但是我不太了解如何實現。

沒有人有任何提示,技巧或示例代碼,可讓您指定根目錄,然后對每個目錄進行爬網(保留字符串數組),直到找不到更多子目錄為止,這樣我就可以從每個目錄中抓取文件了?

要獲取所有子目錄,您必須將SearchOption作為第三個參數傳遞,該參數還將返回所有子目錄。

Directory.GetFiles("","",SearchOption.AllDirectories);

SearchOption

  • SearchOption.AllDirectories :在搜索操作中包括當前目錄及其所有子目錄。 此選項包括重新分析點,例如搜索中的安裝驅動器和符號鏈接。
  • SearchOption.TopDirectoryOnly :在搜索操作中僅包括當前目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM