Open a text file with a Windows Forms dialog

A file dialog chooses a path. It does not guarantee that the subsequent file operation succeeds. Continue only after DialogResult.OK, then handle access or I/O failures where the file is opened.

Supply the owning form so the dialog behaves as a modal child of the application.

Add the file selection action

On Windows, create dotnet new winforms -n FileDialogDemo -f net10.0, replace Program.cs, and run the project.

C#
using System.Windows.Forms;

internal static class Program {
	[STAThread]
	private static void Main() {
		Application.EnableVisualStyles();
		var form = new Form { Width = 600, Height = 400 };
		var text = new TextBox { Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both };
		var open = new Button { Text = "Open text", Dock = DockStyle.Top };
		form.Controls.AddRange([text, open]);
		open.Click += async (_, _) => {
			using var dialog = new OpenFileDialog { Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*" };
			if (dialog.ShowDialog(form) != DialogResult.OK) return;
			try { text.Text = await File.ReadAllTextAsync(dialog.FileName); } catch (IOException ex) { MessageBox.Show(form, ex.Message, "Cannot read file"); } catch (UnauthorizedAccessException ex) { MessageBox.Show(form, ex.Message, "Cannot read file"); }
		};
		Application.Run(form);
	}
}

Select a small UTF-8 text file to display its contents. Cancel leaves the current text unchanged.

Keep format and lifetime limits explicit

The filter helps selection but does not validate the file's contents. Apply size and format limits when opening untrusted or large files. Production forms should cancel or ignore a pending read when the form closes. The example assumes it remains open during the read.

For saving, use SaveFileDialog and check its result before writing. Its overwrite prompt and a later filesystem write are separate events, so write failures still need handling.

Official references

OpenFileDialog Class (System.Windows.Forms)
Displays a standard dialog box that prompts the user to open a file. This class cannot be inherited.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog
OpenFileDialog

Author: Herman Schoenfeld