Winform : How to use Folder and Open File Dialog Controls using C#

winform-folder-file-dialog

When developing projects in Winforms, there will come a time when you will have to deal with Browser Folder and Open File Dialogs. This article will show you how to accomplish common tasks using those two controls in Windows Forms using C#.

As the name suggests, with BrowserFolderDialog control, we select folders and with OpenFileDialog, we select files as shown below:

BrowserFolderDialog control
BrowserFolderDialog
OpenFileDialog control
OpenFileDialog

Here are the most common tasks, when dealing with folder and file dialogs:

How to create Folder Browser Dialog?

string folderpath = "";
FolderBrowserDialog fbd=new FolderBrowserDialog();
DialogResult dr=fbd.ShowDialog();

if (dr == DialogResult.OK)
{
     folderpath=fbd.SelectedPath;
}

if (folderpath!="")
...

How to create Open File Dialog?

string filename = "";

OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr=ofd.ShowDialog();

if (dr == DialogResult.OK)
{
   filename = ofd.FileName;
}
if (filename!="")
...

How to make Open File Dialog to show only files with specific extensions?

For that we use Filters property. Each option contains the description and the filter pattern which is separated by a vertical line |. You can add multiple options which are also separated by a vertical line.
ofd.Filter = "Image Files|*.BMP;*.GIF;*.JPG;*.JPEG;*.PNG|All files (*.*)|*.*"
Open FileDialog Filters

To set which options will be the default, we use FilterIndex property. First Entry always starts with 1 and not 0. With the above example, we would set Index to 2 for "All files".

//To set default to "All files", set the property to 2
ofd.FilterIndex = 2;

How to make Open File Dialog to open in a specific folder?

ofd.InitialDirectory = "c:\\temp";

How to make Open File Dialog to allow the selection of multiple files?

We set MultiSelect property to true and use Filenames property instead of Filename to retrieve a list of selected files.

string[] filenames = {};
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;

DialogResult dr=ofd.ShowDialog();

if (dr == DialogResult.OK)
{
    filenames = ofd.FileNames;
}

I hope you found this article helpful. This article covered only the most basic uses. If you think there is some important task that should be mentioned regarding file browser or folder browser dialog, let me know in the comment section and I might add the task in the future update.

One Response

  1. Panos Metaxas
    June 7, 2018

Write a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.