C# OpenFileDialog Tutorial

OpenFileDialog allows users to browse folders and select files. It is available in Windows Forms and can be used with C# code. It displays the standard Windows dialog box. The results of the selection can be read in your C# code.

OpenFileDialog control in Windows

This C# tutorial demonstrates the OpenFileDialog control in Windows Forms.

Add OpenFileDialog

Steps

First, to begin developing your OpenFileDialog, you need to open your Windows Forms program in the Visual Studio designer and open the Toolbox pane (usually on the left side of Visual Studio's window). Find the OpenFileDialog entry and double-click on it. This entry describes a control that "displays a dialog box that prompts the user to open a file."

How can I modify it? You cannot modify the parts of the OpenFileDialog in the same way as other Windows Forms in the designer. Instead, you can only change properties of it in the Properties pane. To change these properties, select the "openFileDialog1" icon in the tray at the bottom of the Visual Studio window, and then look at the Properties pane.

Showing OpenFileDialog

Here we look at how you can open the OpenFileDialog that is in your Windows Forms program. The dialog will not open automatically and it must be invoked in your custom code. You will want to use an event handler to open the dialog in your C# code. Sometimes, using the Load event (which "occurs whenever the user loads the form") is sufficient to do this. In this tutorial, we will use a button, which when clicked will open the dialog.

Adding Button control. You can add a Button control in Windows Forms through the Visual Studio designer that can be clicked on to call into the OpenFileDialog window. To add a Button, find the Button icon in the Toolbox and drag it to an area in your Windows Forms window. You can add an event to the button click by double-clicking on the "button1" in the designer.

Program that uses OpenFileDialog [C#]

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication18
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void button1_Click(object sender, EventArgs e)
	{
	    // Show the dialog and get result.
	    DialogResult result = openFileDialog1.ShowDialog();
	    if (result == DialogResult.OK) // Test result.
	    {
	    }
	    Console.WriteLine(result); // <-- For debugging use only.
	}
    }
}

Using button1_Click. The above code example demonstrates the use of the openFileDialog1 component that was created in the designer in previous steps. The DialogResult enumerated type is assigned to the result of ShowDialog; this variable is then tested to see what action the user specified to take. The actual strings from the dialog window can be accessed directly as properties on openFileDialog1.

Read files

Note

Here we see an example of how you can access the file specified by the user in the OpenFileDialog, and then read it in using the System.IO namespace methods. We also handle exceptions, preventing some errors related to file system changes that are unavoidable. With this code, when you click on the button the dialog will ask you what file you want. When you accept the dialog, the code will read in that file and print its size in bytes.

Program that reads in file from OpenFileDialog [C#]

using System;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication18
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void button1_Click(object sender, EventArgs e)
	{
	    int size = -1;
	    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
	    if (result == DialogResult.OK) // Test result.
	    {
		string file = openFileDialog1.FileName;
		try
		{
		    string text = File.ReadAllText(file);
		    size = text.Length;
		}
		catch (IOException)
		{
		}
	    }
	    Console.WriteLine(size); // <-- Shows file size in debugging mode.
	    Console.WriteLine(result); // <-- For debugging use only.
	}
    }
}

Description of button1_Click. The event handler in this program is executed when the user clicks on the button1 control. First, an OpenFileDialog as shown in the screenshot at the top of this article is displayed. Second, the DialogResult is tested for the OK value. Next, the FileName property is accessed and the file is read in with File.ReadAllText.

Question and answer

How can I display the file? The above program for simplicity does not have a TextBox control to display the file it opens. If you want to show the file contents in another control, add a TextBox and assign it to the result of File.ReadAllText(file), such as with "textBox1.Text = text;".

Properties

Here we note that the OpenFileDialog control in Windows Forms has many properties that you can set directly in the designer, meaning you do not need to assign them in your own C# code. This section in this article shows some of my notes on these properties, but is not an exhaustive reference.

Environment.SpecialFolder AutoUpgradeEnabled for Open File DialogNote

AddExtension You can change this to False from its default True if you to to automatically fix file extension problems.

AutoUpgradeEnabled This allows you to auomatically get Vista-style open file dialogs. Recommended. See blogs.msdn.com link.

CheckFileExists Leave this as True to give the user a warning when he selects a file that does not exist.

CheckPathExists Same as CheckFileExists (see above) but for paths and directories.

DefaultExt Set this to a string extension for files to automatically add that extension. This is not often useful because very few users type in their file names like this.

DereferenceLinks This tells Windows to resolve shortcuts (aliases) on the system before returning the paths. If you are writing a program that should open the shortcut file themselves, change to False.

FileName You can initialize this in the designer to a preset file name. However this is changed to be the name the user specifies during runtime afterwards.

Filter Use this to specify the file matching filter for the dialog box. The example given is "C# files|*.cs", which will specify that only C# files ending with ".cs" should be shown.

FilterIndex Use to specify the default filter, which will have index of 1. The second filter if one exists would have index of 2.

GenerateMember Not an OpenFileDialog specific property.

InitialDirectory Specify a string here to automatically use that folder as the starting point. See more useful tips on this approach using Environment.SpecialFolder.

Modifiers Not specific to this control.

Multiselect Allows you to specify if multiple files can be selected at once in the dialog. Users can select multiple files by holding SHIFT or CTRL. The default is False.

ReadOnlyChecked This changes the default value of the "read only" checkbox, which is only shown when "ShowReadOnly" is set to True. (See "ShowReadOnly".)

RestoreDirectory You can set this to True to have the dialog reset its location on each use.

ShowHelp Use this to enable the help button on the dialog. If your program uses the help button, you should find more information about it.

ShowReadOnly Whether you want the read-only checkbox to be shown on the dialog. If you have this set to True, you can change "ReadOnlyChecked" to set the actual check state.

SupportMultiDottedExtensions Multi-dotted extensions are extensions that have multiple dots. If you program uses multi-dotted extensions, this is useful.

Tag Not specific to this control.

Title The title of the window, such as "Open File (Dot Net Perls)" in the screenshot.

ValidateNames The Windows file system does not allow files to contain characters such as "*". This option should always be set to True unless your requirements are very unusual.

Summary

The C# programming language

We looked at the extremely useful OpenFileDialog in Windows Forms. Nearly every non-trivial program will need to have an open file dialog, and this control implements this functionality without any problems. We saw how to add an OpenFileDialog, set its properties, use it in C# code, run it when a button is clicked, and read in the actual file when it is specified.

Windows Forms
.NET