共用方式為


如何:使用 OpenFileDialog 開啟檔案

元件 System.Windows.Forms.OpenFileDialog 會開啟 Windows 對話方塊來流覽和選取檔案。 若要開啟並讀取選取的檔案,您可以使用 OpenFileDialog.OpenFile 方法,或建立 類別的 System.IO.StreamReader 實例。 下列範例顯示這兩種方法。

在 .NET Framework 中,若要取得或設定 FileName 屬性,需要 類別授 System.Security.Permissions.FileIOPermission 與的許可權等級。 這些範例會 FileIOPermission 執行許可權檢查,而且在部分信任內容中執行時,可能會因為許可權不足而擲回例外狀況。 如需詳細資訊,請參閱 程式碼存取安全性基本概念

您可以從 C# 或 Visual Basic 命令列建置並執行這些範例作為 .NET Framework 應用程式。 如需詳細資訊,請參閱 使用 csc.exe 建置命令列或 從命令列 建置。

從 .NET Core 3.0 開始,您也可以從具有 .NET Core Windows Forms < 資料夾 name.csproj > 專案檔的資料夾建置和執行範例作為 Windows .NET Core 應用程式。

範例:使用 StreamReader 將檔案讀取為數據流

下列範例會使用 Windows Forms Button 控制項的 Click 事件處理常式,以 ShowDialog 方法開啟 OpenFileDialog 。 使用者選擇檔案並選取 [確定 ] 之後,類別的 StreamReader 實例會讀取檔案,並在表單的文字方塊中顯示其內容。 如需從檔案資料流程讀取的詳細資訊,請參閱 FileStream.BeginReadFileStream.Read

using System;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;

public class OpenFileDialogForm : Form
{
    [STAThread]
    public static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new OpenFileDialogForm());
    }

    private Button selectButton;
    private OpenFileDialog openFileDialog1;
    private TextBox textBox1;

    public OpenFileDialogForm()
    {
        openFileDialog1 = new OpenFileDialog();
        selectButton = new Button
        {
            Size = new Size(100, 20),
            Location = new Point(15, 15),
            Text = "Select file"
        };
        selectButton.Click += new EventHandler(SelectButton_Click);
        textBox1 = new TextBox
        {
            Size = new Size(300, 300),
            Location = new Point(15, 40),
            Multiline = true,
            ScrollBars = ScrollBars.Vertical
        };
        ClientSize = new Size(330, 360);
        Controls.Add(selectButton);
        Controls.Add(textBox1);
    }
    private void SetText(string text)
    {
        textBox1.Text = text;
    }
    private void SelectButton_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                var sr = new StreamReader(openFileDialog1.FileName);
                SetText(sr.ReadToEnd());
            }
            catch (SecurityException ex)
            {
                MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
                $"Details:\n\n{ex.StackTrace}");
            }
        }
    }
}
Imports System.Drawing
Imports System.IO
Imports System.Security
Imports System.Windows.Forms

Public Class OpenFileDialogForm : Inherits Form

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.EnableVisualStyles()
        Dim frm As New OpenFileDialogForm()
        Application.Run(frm)
    End Sub

    Dim WithEvents SelectButton As Button
    Dim openFileDialog1 As OpenFileDialog
    Dim TextBox1 As TextBox

    Private Sub New()
        ClientSize = New Size(400, 400)
        openFileDialog1 = New OpenFileDialog()
        SelectButton = New Button()
        With SelectButton
            .Text = "Select file"
            .Location = New Point(15, 15)
            .Size = New Size(100, 25)
        End With
        TextBox1 = New TextBox()
        With TextBox1
            .Size = New Size(300, 300)
            .Location = New Point(15, 50)
            .Multiline = True
            .ScrollBars = ScrollBars.Vertical
        End With
        Controls.Add(SelectButton)
        Controls.Add(TextBox1)
    End Sub

    Private Sub SetText(text)
        TextBox1.Text = text
    End Sub

    Public Sub SelectButton_Click(sender As Object, e As EventArgs) _
              Handles SelectButton.Click
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                Dim sr As New StreamReader(openFileDialog1.FileName)
                SetText(sr.ReadToEnd())
            Catch SecEx As SecurityException
                MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
                $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
            End Try
        End If
    End Sub
End Class

範例:使用 OpenFile 從篩選的選取範圍開啟檔案

下列範例會使用 Button 控制項的事件處理常式,以只顯示文字檔的 Click 篩選來開啟 OpenFileDialog 。 使用者選擇文字檔並選取 [ 確定 ] 之後, OpenFile 方法會用來在 記事本中開啟檔案。

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;

public class OpenFileDialogForm : Form
{
    [STAThread]
    public static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new OpenFileDialogForm());
    }

    private Button selectButton;
    private OpenFileDialog openFileDialog1;

    public OpenFileDialogForm()
    {
        openFileDialog1 = new OpenFileDialog()
        {
            FileName = "Select a text file",
            Filter = "Text files (*.txt)|*.txt",
            Title = "Open text file"
        };

        selectButton = new Button()
        {
            Size = new Size(100, 20),
            Location = new Point(15, 15),
            Text = "Select file"
        };
        selectButton.Click += new EventHandler(selectButton_Click);
        Controls.Add(selectButton);
    }

    private void selectButton_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                var filePath = openFileDialog1.FileName;
                using (Stream str = openFileDialog1.OpenFile())
                {
                    Process.Start("notepad.exe", filePath);
                }
            }
            catch (SecurityException ex)
            {
                MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
                $"Details:\n\n{ex.StackTrace}");
            }
        }
    }
}
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.IO
Imports System.Security
Imports System.Windows.Forms

Public Class OpenFileDialogForm : Inherits Form
    Dim WithEvents selectButton As Button
    Dim openFileDialog1 As OpenFileDialog

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(false)
        Application.EnableVisualStyles()
        Dim frm As New OpenFileDialogForm()
        Application.Run(frm)
    End Sub

    Private Sub New()
        openFileDialog1 = New OpenFileDialog() With
        {
           .FileName = "Select a text file",
           .Filter = "Text files (*.txt)|*.txt",
           .Title = "Open text file"
        }

        selectButton = New Button() With {.Text = "Select file"}
        Controls.Add(selectButton)
    End Sub

    Public Sub selectButton_Click(sender As Object, e As EventArgs) _
            Handles selectButton.Click
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                Dim filePath = OpenFileDialog1.FileName
                Using str = openFileDialog1.OpenFile()
                    Process.Start("notepad.exe", filePath)
                End Using
            Catch SecEx As SecurityException
                MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
                $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
            End Try
        End If
    End Sub
End Class

另請參閱