Title: Let the user select a folder in C#
This example demonstrates two handy techniques. First, it lets you select a folder. When you click the program's ellipsis button, the following code displays a FolderBrowserDialog. This lets the user pick a directory instead of needing to type it in.
// Display the folder browser dialog.
private void btnPickDirectory_Click(object sender, EventArgs e)
{
fbdDirectory.SelectedPath = txtDirectory.Text;
if (fbdDirectory.ShowDialog() == DialogResult.OK)
{
txtDirectory.Text = fbdDirectory.SelectedPath;
}
}
The code initializes the dialog to the directory path in the text box. If this is not a valid path, the dialog defaults to its directory hierarchy root, in this case the Desktop. You can change the root by setting the dialog's RootFolder property at design time.
After it initializes the dialog, the program displays it modally. It's unfortunate that the dialog is so clunky but it's what Microsoft has given us. Something more along the lines of Windows Explorer would have been better.
The second useful technique is that the program saves the user's selection between runs. At design time I created a setting named Directory. To create a setting, double-click the Properties entry in Solution Explorer and go to the Settings tab.
When it starts, the program uses the following code to load the value saved in this setting.
// Restore the saved directory.
private void Form1_Load(object sender, EventArgs e)
{
txtDirectory.Text = Properties.Settings.Default.Directory;
}
The program uses the following code to save the current selection when the form closes.
// Save the current directory.
private void Form1_FormClosing(object sender,
FormClosingEventArgs e)
{
Properties.Settings.Default.Directory = txtDirectory.Text;
Properties.Settings.Default.Save();
}
Download the example to experiment with it and to see additional details.
|