Como: Abrir arquivos com OpenFileDialogHow to: Open files with the OpenFileDialog

O System.Windows.Forms.OpenFileDialog componente abre a caixa de diálogo do Windows para procurar e selecionar os arquivos.The System.Windows.Forms.OpenFileDialog component opens the Windows dialog box for browsing and selecting files. Para abrir e ler os arquivos selecionados, você pode usar o OpenFileDialog.OpenFile método, ou crie uma instância da System.IO.StreamReader classe.To open and read the selected files, you can use the OpenFileDialog.OpenFile method, or create an instance of the System.IO.StreamReader class. Os exemplos a seguir mostram as duas abordagens.The following examples show both approaches.

No .NET Framework, para obter ou definir a FileName propriedade requer um nível de privilégio concedido pela System.Security.Permissions.FileIOPermission classe.In .NET Framework, to get or set the FileName property requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. Os exemplos executam um FileIOPermission permissão verificar e pode lançar uma exceção devido a privilégios insuficientes se executado em um contexto de confiança parcial.The examples run a FileIOPermission permission check, and can throw an exception due to insufficient privileges if run in a partial-trust context. Para obter mais informações, consulte Noções básicas sobre segurança de acesso do código.For more information, see Code access security basics.

Você pode compilar e executar esses exemplos que os aplicativos do .NET Framework a C# ou a linha de comando do Visual Basic.You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. Para obter mais informações, consulte linha de comando compilando com csc.exe ou compilar da linha de comando.For more information, see Command-line building with csc.exe or Build from the command line.

Começando com o .NET Core 3.0, você pode também compilar e executar os exemplos de como os aplicativos .NET Core do Windows de uma pasta que tem um .NET Core Windows Forms <nome da pasta >. csproj arquivo de projeto.Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms <folder name>.csproj project file.

Exemplo: Ler um arquivo como um fluxo com um StreamReaderExample: Read a file as a stream with StreamReader

O exemplo a seguir usa o Windows Forms Button do controle Click manipulador de eventos para abrir o OpenFileDialog com o ShowDialog método.The following example uses the Windows Forms Button control's Click event handler to open the OpenFileDialog with the ShowDialog method. Depois que o usuário escolhe um arquivo e seleciona Okey, uma instância da StreamReader classe lê o arquivo e exibe seu conteúdo na caixa de texto do formulário.After the user chooses a file and selects OK, an instance of the StreamReader class reads the file and displays its contents in the form's text box. Para obter mais informações sobre a leitura de fluxos de arquivos, consulte FileStream.BeginRead e FileStream.Read.For more information about reading from file streams, see FileStream.BeginRead and FileStream.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

Exemplo: Abrir um arquivo de uma seleção filtrada com OpenFileExample: Open a file from a filtered selection with OpenFile

O exemplo a seguir usa o Button do controle Click manipulador de eventos para abrir o OpenFileDialog com um filtro que mostra apenas os arquivos de texto.The following example uses the Button control's Click event handler to open the OpenFileDialog with a filter that shows only text files. Depois que o usuário escolhe um arquivo de texto e seleciona Okey, o OpenFile método é usado para abrir o arquivo no bloco de notas.After the user chooses a text file and selects OK, the OpenFile method is used to open the file in Notepad.

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

Consulte tambémSee also