核心屬性速查表
| 屬性 | 說明 | 範例值 |
| InitialDirectory | 初始目錄 | @"C:\" 或 Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) |
| Filter | 檔案類型過濾器 | "文字檔|*.txt|C#檔|*.cs|所有檔|*.*" |
| FilterIndex | 預設選取的過濾器索引 (1-based) | 1 |
| RestoreDirectory | 關閉前恢復目前目錄 | true |
| Title | 對話方塊標題 | "請選擇要開啟的檔案" |
| CheckFileExists | 檢查檔案是否存在 | true |
| CheckPathExists | 檢查路徑是否存在 | true |
| Multiselect | 允許多選 | false (預設) |
常用事件
FileOk:使用者點擊「開啟」後、對話方塊關閉前觸發,可在此驗證檔案。
HelpRequest:點擊「說明」按鈕觸發。
基本使用範例
private void btnOpenFile_Click(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog())
{
dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialog.Filter = "文字檔 (*.txt)|*.txt|C# 程式碼 (*.cs)|*.cs|所有檔案 (*.*)|*.*";
dialog.FilterIndex = 1;
dialog.RestoreDirectory = true;
dialog.Title = "選擇要開啟的檔案";
if (dialog.ShowDialog() == DialogResult.OK)
{
string filePath = dialog.FileName;
// 讀取檔案內容 (現代寫法)
try
{
string content = File.ReadAllText(filePath, Encoding.UTF8);
txtContent.Text = content;
this.Text = $"編輯中 - {filePath}";
}
catch (Exception ex)
{
MessageBox.Show($"讀取檔案失敗:{ex.Message}", "錯誤",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
進階:多選檔案處理
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
foreach (string file in dialog.FileNames)
{
// 處理每個檔案
ProcessFile(file);
}
}
資料夾瀏覽對話方塊
private void btnBrowseFolder_Click(object sender, EventArgs e)
{
using (var dialog = new FolderBrowserDialog())
{
dialog.Description = "請選擇資料夾";
dialog.ShowNewFolderButton = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
txtFolderPath.Text = dialog.SelectedPath;
}
}
}
最佳實踐總結
- 使用 using 區塊:確保對話方塊資源正確釋放。
- 指定編碼讀取:
File.ReadAllText(path, Encoding.UTF8) 避免中文亂碼。
- 設定合理的初始目錄:使用
Environment.SpecialFolder 而非硬編碼路徑。
- 過濾器格式:
"描述|副檔名|描述2|副檔名2",以 | 分隔,雙管道 || 結尾。
- 錯誤處理:檔案 I/O 操作務必包裹在 try-catch 中。