Introduction
This article is not of interest to advanced programmers, as it answers the following questions:
- How to use
SelectedPath
property of FolderBrowserDialog
class? - How to open a
FolderBrowserDialog
at the selected logical drive?
But...
Background
Despite the fact that the MSDN provides a clear definition of RootFolder
and SelectedPath
properties, it cited the examples do not provide a clear view.
I'll try to fill this gap.
Using the Code
Run an application and fill comboBox1
the next items:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Browse...");
foreach (var Drives in Environment.GetLogicalDrives())
{
DriveInfo DriveInf = new DriveInfo(Drives);
if (DriveInf.IsReady == true)
{
comboBox1.Items.Add(DriveInf.Name);
}
}
}
If you want to explore how to work a SelectedPath
property dynamically - add any subfolder to the comboBox1
.
For this:
- Select an item (any drive)
comboBox1
control. - This is will open
FolderBrowserDialog
at the item. - In the
FolderBrowserDialog
, select any subfolder from the tree file system and click <OK>.
The path of selected subfolder is added to collection items comboBox1
. - Select new item.
As result is opened and deployed, the FolderBrowserDialog
with the RootFolder
and any subfolders
that are beneath it will appear in the dialog box and be selectable.
NOTE:
The SelectedPath
is an absolute path that is a subfolder of RootFolder
.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string item = comboBox1.SelectedItem.ToString();
FolderBrowserDialog fbd = new FolderBrowserDialog();
OpenFolderBrowserDialog(fbd, item);
}
private void OpenFolderBrowserDialog(FolderBrowserDialog folderBrowserDialog, string item)
{
folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
folderBrowserDialog.SelectedPath = item;
folderBrowserDialog.ShowNewFolderButton = false;
try
{
DialogResult dr = folderBrowserDialog.ShowDialog();
if (dr == DialogResult.OK)
{
comboBox1.Items.Add(folderBrowserDialog.SelectedPath);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
On the other hand:
If "Browse..." has been selected in comboBox1
control, I see no reason to suppose that someone there is a folder with the same name, SelectedPath
does not work and as a result, FolderBrowserDialog
will be opened with the RootFolder=Environment.SpecialFolder.Desktop
only!
We see that "...as long as SelectedPath is set to an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder)". (MSDN)
History
- March 23, 2016: Article published