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:
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?
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.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".
How to make Open File Dialog to open in a specific folder?
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.
Panos Metaxas
June 7, 2018Thank you very much! You helped me, after searching for hours for a solution!