WinForm 應用常需讓使用者選擇資料夾,或遞迴搜尋特定副檔名檔案。本文提供兩個實用工具類:MyFolderDialog 封裝資料夾瀏覽對話框,GetSubDirectoryAndFiles 實作遞迴檔案搜尋。
繼承 System.Windows.Forms.Design.FolderNameEditor,存取其內部 FolderBrowser。
using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
public class MyFolderDialog : FolderNameEditor
{
private FolderBrowser fDialog = new FolderBrowser();
public MyFolderDialog()
{
// 設定瀏覽風格:可瀏覽所有、顯示文字方塊
fDialog.Style = FolderBrowserStyles.BrowseForEverything | FolderBrowserStyles.ShowTextBox;
// 起始位置:我的電腦
fDialog.StartLocation = FolderBrowserFolder.MyComputer;
}
/// 顯示對話框,預設提示訊息
public DialogResult DisplayDialog()
{
return DisplayDialog("請選擇一個資料夾");
}
/// 顯示對話框,自訂提示訊息
public DialogResult DisplayDialog(string description)
{
fDialog.Description = description;
return fDialog.ShowDialog();
}
/// 使用者選擇的路徑
public string Path
{
get { return fDialog.DirectoryPath; }
}
// 解構函式釋放資源
~MyFolderDialog()
{
fDialog.Dispose();
}
}
public string GetDir()
{
using (var dialog = new MyFolderDialog())
{
if (dialog.DisplayDialog() == DialogResult.OK)
return dialog.Path;
return string.Empty;
}
}
System.Design.dll(專案 → 加入參考 → 組件 → Framework → System.Design)System.Windows.Forms.Designusing System;
using System.IO;
using System.Collections.Generic;
public class FileSearcher
{
///
/// 遞迴搜尋指定目錄下所有符合副檔名的檔案
///
/// 起始目錄完整路徑
/// 副檔名(含點,如 ".dwg")
/// 符合條件的檔案完整路徑清單
public List GetFilesByExtension(string fullName, string extension)
{
var result = new List();
GetSubDirectoryAndFiles(fullName, extension, result);
return result;
}
private void GetSubDirectoryAndFiles(string fullName, string extension, List outFiles)
{
DirectoryInfo dir = new DirectoryInfo(fullName);
// 遞迴處理子目錄
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
// 跳過隱藏目錄
if ((subDir.Attributes & FileAttributes.Hidden) != 0)
continue;
GetSubDirectoryAndFiles(subDir.FullName, extension, outFiles);
}
// 當前目錄搜尋檔案
foreach (FileInfo file in dir.GetFiles(extension))
{
outFiles.Add(file.FullName);
}
}
}
var searcher = new FileSearcher();
var dwgFiles = searcher.GetFilesByExtension(@"D:\Projects", ".dwg");
foreach (var file in dwgFiles)
Console.WriteLine(file);
Task.Run 避免 UI 凍結IProgress<T> 回報搜尋進度CancellationToken 讓使用者中止string[] extensions 或 SearchOption.AllDirectories 簡化Parallel.ForEach 加速目錄遍歷MyFolderDialog 封裝系統設計時資料夾瀏覽器,提供簡潔 API;遞迴搜尋採用深度優先策略,跳過隱藏目錄,支援任意副檔名過濾。兩者結合可構建完整的檔案選擇與搜尋功能。