Select a File with OpenFileDialog in C# (WinForms)

OpenFileDialog shows the standard Windows “Open” dialog and returns the path of the file the user picked. It only selects; reading the file is up to you. The class is in System.Windows.Forms, so this is Windows-only: the project targets net8.0-windows with UseWindowsForms, as created by dotnet new winforms:

<PropertyGroup>
  <OutputType>WinExe</OutputType>
  <TargetFramework>net8.0-windows</TargetFramework>
  <UseWindowsForms>true</UseWindowsForms>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Open a text file

private async void OpenButton_Click(object? sender, EventArgs e)
{
    using var dialog = new OpenFileDialog
    {
        Title = "Open a text file",
        Filter = "Text files (*.txt)|*.txt|Log files (*.log)|*.log|All files (*.*)|*.*",
        InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    };

    if (dialog.ShowDialog(this) != DialogResult.OK)
    {
        return;
    }

    try
    {
        contentTextBox.Text = await File.ReadAllTextAsync(dialog.FileName);
        Text = dialog.SafeFileName;
    }
    catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
    {
        MessageBox.Show(this, ex.Message, "Could not open the file",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

FileName is the full path; SafeFileName is just the name and extension, handy for a window title. Reading with ReadAllTextAsync in an async void event handler keeps the window responsive while a large file loads, and the assignment to contentTextBox.Text after await runs back on the UI thread. ReadAllTextAsync detects a byte order mark and otherwise assumes UTF-8; pass an Encoding if your files use something else.

The try/catch is not optional. The file can be locked by another program, deleted between selection and reading, or sit on a network share you have no permission to read.

The filter string

Filter takes pairs separated by |: a description, then one or more patterns separated by semicolons:

Images (*.png;*.jpg;*.gif)|*.png;*.jpg;*.gif|All files (*.*)|*.*

An odd number of parts throws an ArgumentException when you assign the property. FilterIndex chooses the entry shown first and starts at 1, not 0. The filter only controls what the dialog lists; a user can type *.* into the file name box or paste any path, so validate the file you get.

Selecting several files

using var dialog = new OpenFileDialog
{
    Filter = "Images (*.png;*.jpg)|*.png;*.jpg",
    Multiselect = true
};

if (dialog.ShowDialog(this) == DialogResult.OK)
{
    foreach (string path in dialog.FileNames)
    {
        imageListBox.Items.Add(Path.GetFileName(path));
    }
}

With Multiselect on, read FileNames (plural). FileName still works but only holds the first selection.

Useful properties

PropertyDefaultWhat it does
CheckFileExiststrueRejects names of files that don’t exist.
CheckPathExiststrueRejects paths to folders that don’t exist.
MultiselectfalseAllows selecting several files.
ReadOnlyChecked, ShowReadOnlyfalseShows an “Open as read-only” check box and reports its state.
RestoreDirectoryfalseRestores the process’s current directory after the dialog closes.

Set RestoreDirectory = true if any of your code uses relative paths. Browsing in the dialog can change Environment.CurrentDirectory, and relative paths that worked a minute ago then point somewhere else.

OpenFile() opens the selected file read-only and returns a Stream, which saves a line when you pass the file to something that takes a stream, such as Image.FromStream.

STA threads and other UI frameworks

Common dialogs need a single-threaded apartment (STA) thread. WinForms apps mark Main with [STAThread], so it just works there. Showing the dialog from a console app or a background thread throws a ThreadStateException; add [STAThread] to Main in that case, and never show dialogs from worker threads.

To pick a folder instead of a file, use FolderBrowserDialog. WPF has its own Microsoft.Win32.OpenFileDialog with a very similar API, and since .NET 8 also Microsoft.Win32.OpenFolderDialog.

Related examples

Leave a Comment