OpenFileDialog, SaveFileDialog, FolderBrowserDialog

A desktop application asks the operating system for a file rather than drawing a file browser of its own. Three dialogs do that: OpenFileDialog to choose one or several existing files, SaveFileDialog to choose a name for a new one, and FolderBrowserDialog to choose a folder. All three are modal, all three return a DialogResult, and none of them opens the file.

OpenFileDialog

using System; using System.Drawing; using System.IO; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly RichTextBox _editor = new() { Dock = DockStyle.Fill }; public Form1() { Text = "Open a note"; ClientSize = new Size(520, 320); var open = new Button { Text = "&Open", Dock = DockStyle.Top }; open.Click += (sender, e) => Open(); Controls.Add(_editor); Controls.Add(open); } private void Open() { using var dialog = new OpenFileDialog { Title = "Open a note", Filter = "Text files (*.txt)|*.txt|Rich text (*.rtf)|*.rtf|All files (*.*)|*.*", FilterIndex = 1, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), CheckFileExists = true, Multiselect = false, }; if (dialog.ShowDialog(this) != DialogResult.OK) { return; } var path = dialog.FileName; _editor.Text = File.ReadAllText(path); Text = Path.GetFileName(path); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The dialog is created in a using statement because it holds a handle to the shell's dialog; the ShowDialog(this) makes it modal to the form; and FileName is the only property that matters after the user confirmed. CheckFileExists makes the dialog itself refuse a name that is not there, so the code after it does not need the check.

With Multiselect = true the result is in FileNames, an array, and FileName holds only the first. The open in a text editor is the case for the single name; an import that merges several files is the case for the array.

The filter

The Filter string is a list of pairs separated by a vertical bar: the description the user sees, then the pattern. The pattern of a pair may hold several extensions separated by semicolons:

Text files (*.txt)|*.txt|Rich text (*.rtf)|*.rtf|All files (*.*)|*.*

Three details of the syntax cost an afternoon to whoever meets them first. A pattern must not contain spaces around the semicolon. FilterIndex counts from 1, not from 0, so the first group is 1. And the description is free: it may say *.txt or not, and the dialog shows it as written. A filter with an odd number of parts is a runtime error when the dialog opens, and the real message names the property.

SaveFileDialog

using System; using System.Drawing; using System.IO; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly RichTextBox _editor = new() { Dock = DockStyle.Fill }; public Form1() { Text = "Save a note"; ClientSize = new Size(520, 320); var save = new Button { Text = "&Save as", Dock = DockStyle.Top }; save.Click += (sender, e) => SaveAs(); Controls.Add(_editor); Controls.Add(save); } private void SaveAs() { using var dialog = new SaveFileDialog { Title = "Save the note", Filter = "Text files (*.txt)|*.txt|Rich text (*.rtf)|*.rtf", DefaultExt = "txt", AddExtension = true, OverwritePrompt = true, FileName = "untitled.txt", }; if (dialog.ShowDialog(this) != DialogResult.OK) { return; } File.WriteAllText(dialog.FileName, _editor.Text); Text = Path.GetFileName(dialog.FileName); } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. DefaultExt and AddExtension = true are the pair that makes a user who types notes get notes.txt, and OverwritePrompt is the confirmation the shell shows before it returns a name that already exists. Without the pair, a file without an extension is created and the editor that opens it next week cannot guess the format.

A SaveFileDialog does not save anything: it returns a name. The write is the program's, which is why the listing uses File.WriteAllText and not a method of the dialog. The one exception is OpenFileDialog.OpenFile(), which returns a Stream on the chosen file, and it is used when the program wants to read the file before closing the dialog.

FolderBrowserDialog

using System; using System.Drawing; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly ListBox _recent = new() { Dock = DockStyle.Fill }; public Form1() { Text = "A library folder"; ClientSize = new Size(460, 260); var pick = new Button { Text = "Choose &folder", Dock = DockStyle.Top }; pick.Click += (sender, e) => { using var dialog = new FolderBrowserDialog { Description = "Where the notes are kept", UseDescriptionForTitle = true, ShowNewFolderButton = true, }; if (dialog.ShowDialog(this) == DialogResult.OK) { _recent.Items.Add(dialog.SelectedPath); } }; Controls.Add(_recent); Controls.Add(pick); } }

That block is a fragment as well, and it is the third way to ask for a path. SelectedPath is the result; UseDescriptionForTitle = true shows the description where the dialog's title would be, which is the only way to put a sentence into FolderBrowserDialog in .NET 10. The dialog shows no files, only folders, and the ShowNewFolderButton flag is what lets the user make one.

A program that lets the user choose a file but wants the modern shell dialog of Windows Vista and later uses OpenFileDialog with its AutoUpgradeEnabled property (on by default) and nothing else; the older FolderBrowserDialog is the one dialog that still looks like Windows 2000, which is why a form that needs a good folder picker often uses a custom dialog or the Windows API. That route is in the interop lesson, in words.

A filter that runs

The filter is a small grammar, and parsing it is worth doing once: a dialog shows the user the description and matches the pattern, and a program that imports a dropped file applies the same pattern. This program splits a filter and matches three names, and it runs here:

using System; var filter = "Text files (*.txt)|*.txt|Images (*.png;*.jpg)|*.png;*.jpg|All files (*.*)|*.*"; var parts = filter.Split('|'); for (var i = 0; i + 1 < parts.Length; i += 2) { Console.WriteLine($"group {i / 2 + 1}: {parts[i]} -> {parts[i + 1]}"); } Console.WriteLine($"notes.txt in *.txt: {Accepts("*.txt", "notes.txt")}"); Console.WriteLine($"photo.png in images: {Accepts("*.png;*.jpg", "photo.png")}"); Console.WriteLine($"notes.txt in images: {Accepts("*.png;*.jpg", "notes.txt")}"); Console.WriteLine($"groups: {parts.Length / 2}"); static bool Accepts(string patterns, string name) { foreach (var pattern in patterns.Split(';')) { var suffix = pattern.TrimStart('*'); if (name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; }

dotnet run

group 1: Text files (*.txt) -> *.txt
group 2: Images (*.png;*.jpg) -> *.png;*.jpg
group 3: All files (*.*) -> *.*
notes.txt in *.txt: True
photo.png in images: True
notes.txt in images: False
groups: 3

The output is the real run. The split on the bar gives the pairs, and the count divides by two, which is the check that a filter is well formed. The matcher reduces a simple *.ext pattern to its suffix and compares the end of the name, which is enough for the filters a form writes and deliberately not a general wildcard match: a pattern with a question mark or a name prefix needs FileSystemName.MatchesSimpleExpression or a regular expression.

Exercises

  1. Add a fourth group for bitmaps and run the program. What does groups print?
  2. Make the matcher accept a pattern without the leading star, and run it with notes.txt.txt.
  3. Explain from the documentation what OpenFileDialog.OpenFile is for and when the program should not use it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a file dialog return?

    Answer

    A DialogResult, and the path in FileName or FileNames

    The dialog chooses a name; the program opens it.

  2. What separates the description from the pattern in a Filter?

    Answer

    A vertical bar

    The semicolon separates several extensions inside one pattern.

  3. Which value of FilterIndex selects the first group?

    Answer

    1

    FilterIndex counts from one, unlike most collections.

  4. Which pair gives a saved file an extension the user did not type?

    Answer

    DefaultExt and AddExtension = true

    Without them a file called notes is created and cannot be opened by association.

  5. What does OverwritePrompt do?

    Answer

    Asks before returning a name that already exists

    It is the shell's confirmation, and it is on by default for a save dialog.

  6. Where is the result of a Multiselect open?

    Answer

    FileNames, an array

    FileName holds only the first of the names.

  7. How does a program show a sentence in a FolderBrowserDialog in .NET 10?

    Answer

    Description with UseDescriptionForTitle = true

    The folder picker has no title of its own.

  8. What did the run print for notes.txt against the images pattern?

    Answer

    False

    Neither .png nor .jpg is a suffix of the name.

  9. Why is a pattern with an odd number of parts an error?

    Answer

    The dialog expects description and pattern in pairs

    The run's count of groups is the check.

  10. Which call opens the chosen file as a stream?

    Answer

    OpenFileDialog.OpenFile()

    It is the one file operation the dialog does itself.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev