示範如何使用 OpenFileDialog 讓使用者選取檔案,再透過 Process.Start 呼叫系統關聯程式開啟該檔案。
private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.DefaultExt = "xls";
dlg.Filter = "Excel 檔案 (*.xls)|*.xls|所有檔案 (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
txtSourceFileName.Text = dlg.FileName;
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
string filePath = txtSourceFileName.Text;
if (File.Exists(filePath))
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = filePath,
UseShellExecute = true // 使用系統關聯程式
};
Process.Start(psi);
}
catch (Exception ex)
{
MessageBox.Show($"無法開啟檔案: {ex.Message}");
}
}
else
{
MessageBox.Show("檔案不存在。");
}
}
UseShellExecute = true 可讓作業系統依副檔名自動選擇開啟程式。
延伸應用: 指定開啟程式、列印檔案、編輯檔案等 Verb 操作。