Click here to Skip to main content
15,867,321 members
Articles / Programming Languages / C#
Article

Folder Select Dialog

Rate me:
Please Sign up or sign in to vote.
4.46/5 (14 votes)
1 Jan 20023 min read 349.7K   4.7K   61   27
An article on how to use the .NET TreeView and Directory Info object to construct a folder selection dialog.

Folder Select Dialog

Introduction

This article describes the implementation of a simple Folder Selection dialog using C#. After designing my latest project, I found a need for a simple, easy to implement folder selection dialog for C#. The OpenFileDialog class did not suite my needs, and to integrate the COM interface to the SHBrowseForFolder, was a little more complicated that the solution I present here.

The basic dialog is built with the standard winform architecture.  by modifying the window style, you can make the dialog appear as a standard windows dialog, or as a sizable window, which is the default for this example.  this example was put together using Visual Studio .Net beta 2, and the IDE was used to construct the basic functionality of the UI. 

Implementation

Three events are used in this dialog, OnBeforeSelect, OnBeforeExpand, and OnButtonClick. The first events are generated by the TreeView control.  The OnBeforeSelect and OnBeforeExpand events both perform similar tasks.  Each time the user selects a folder or clicks to expand a tree node, these events are triggered and upon receiving these events will scan the selected node identified by the Node parameter in the TreeViewCancelEventArgs class.

C#
private void treeView1_BeforeSelect(object sender, 
                                    System.Windows.Forms.TreeViewCancelEventArgs e)
{
    getSubDirs(e.Node);                    // get the sub-folders for the selected node.
    textBox1.Text = fixPath(e.Node);        // update the user selection text box.
    folder = new DirectoryInfo(e.Node.FullPath);    // get it's Directory info.
}

private void treeView1_BeforeExpand(object sender, 
                                    System.Windows.Forms.TreeViewCancelEventArgs e)
{
    getSubDirs(e.Node);                    // get the sub-folders for the selected node.
    textBox1.Text = fixPath(e.Node);        // update the user selection text box.
    folder = new DirectoryInfo(e.Node.FullPath);    // get it's Directory info.
}

Folder select tree building

Both event handlers call a sub method called getSubDirs().  This method will scan for any sub-folders for the given folder.  If this folder has been visited before, no scan is done, since it has already been entered into the tree control.  Note that this does imply that if the directory structure on the hard drive your examining changes, it will not be reflected in the dialog until it has been reopened.  As the user navigates to a folder, the TreeView control stores the data needed to construct a full path to the folder that the user selected.  When the dialog is closed with the Select button, a DirectoryInfo variable "folder" is loaded with the DirectoryInfo information retrieved when a new instance of this class is created.  The folder information is stored for later access by the application.

C#
private void getSubDirs( TreeNode parent )
{
    DirectoryInfo directory;
    try
    {
        if ( parent.Nodes.Count == 0 )
        {
            directory = new DirectoryInfo(parent.FullPath);
            foreach( DirectoryInfo dir in directory.GetDirectories())
            {
                TreeNode newNode = new TreeNode(dir.Name);
                parent.Nodes.Add(newNode);
            }
        }

        foreach(TreeNode node in parent.Nodes)
        {
            if (node.Nodes.Count == 0)
            {
                directory = new DirectoryInfo(node.FullPath);
                foreach( DirectoryInfo dir in directory.GetDirectories())
                {
                    TreeNode newNode = new TreeNode(dir.Name);
                    node.Nodes.Add(newNode);
                }
            }
        }
    }
    catch( Exception doh )
    {
        Console.WriteLine(doh.Message);
    }
}

Folder select Properties

After closing the folder select dialog with the select button, your application can retrieve the folder information by calling the public properties

fullPath, 
                name, 
and info. These properties will allow for easy retrieval of any information stored within the DirectoryInfo class.

C#
public string name
{
    get { return ((folder != null && folder.Exists))? folder.Name : null; }
}

public string fullPath
{
    get { return ((folder != null && folder.Exists && 
          treeView1.SelectedNode != null))? fixPath(treeView1.SelectedNode) : null; }
}

public DirectoryInfo info
{
    get { return ((folder != null && folder.Exists))? folder : null; }
}

Implementation details

Accessing the properties you will notice that we call a private method fixPath() to correct a problem I discovered with building the tree. The treeView will only work with paths constructed like the following example. "c:\\Program Files\Microsoft\...". What this fixPath() does is strip the leading "\\" next to the drive letter and replace it with a single "\". This should be compatible with UNC names as we expect to have a drive letter at the beginning of the string in order to correct the problem.

C#
private string fixPath( TreeNode node )
{
    string sRet = "";
    try
    {
        sRet = node.FullPath;
        int index = sRet.IndexOf("\\\\");
        if (index > 1 )
        {
            sRet = node.FullPath.Remove(index, 1);
        }
    }
    catch( Exception doh )
    {
        Console.WriteLine(doh.Message);
    }
    return sRet;
}

Dialog invocation code

Here is an example of invoking the folder select dialog.

C#
// invoke the folder select dialog
private void button1_Click(object sender, System.EventArgs e)
{
    try 
    {
        FolderSelect dlg = new FolderSelect();

        if ( dlg.ShowDialog() == DialogResult.OK)
        {
            DirectoryInfo info = dlg.info;
            textBox1.Text = dlg.fullPath;

            // extract the directory info.
            string [] strArray = new string[4];

            strArray[0] = "Creation Time : "+ info.CreationTime.ToString();
            strArray[1] =    "Full Name     : "+ info.FullName;
            strArray[2] = "Last Access Time : "+ info.LastAccessTime.ToString();
            strArray[3] = "Last Write Time  : "+ info.LastWriteTime.ToString();

            textBox3.Lines = strArray;
        }
    }
    catch( Exception err)
    {
        Console.WriteLine(err.Message);
    }
}

Summary

This is just a very simple Windows Form dialog. This should give you a starting point to build upon. I am not an expert on C# or Forms application at least not yet. Please do send your comments and suggestions to me. I will try to improve this application and add some more advanced features.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to open Select User Dialog box in C#? Pin
Sunil G 33-Nov-09 6:49
Sunil G 33-Nov-09 6:49 
Questionin a php/html/javascript form??? Pin
fcois9323-May-08 0:36
fcois9323-May-08 0:36 
Generalc# System.Windows.Forms.FolderBrowserDialog [modified] Pin
phanf6-Aug-07 6:09
phanf6-Aug-07 6:09 
GeneralSome Modifications Pin
yousef.omar27-Mar-05 23:21
yousef.omar27-Mar-05 23:21 
GeneralRe: Some Modifications Pin
yousef.omar27-Mar-05 23:38
yousef.omar27-Mar-05 23:38 
GeneralFrom MS Pin
Anonymous13-Oct-03 10:07
Anonymous13-Oct-03 10:07 
GeneralRe: From MS Pin
Chris Warner14-Oct-03 7:22
Chris Warner14-Oct-03 7:22 
GeneralRe: From MS Pin
sfeldi10-May-06 20:59
sfeldi10-May-06 20:59 
QuestionHow to use Pin
musicway12-Jun-03 22:16
musicway12-Jun-03 22:16 
AnswerRe: How to use Pin
Chris Warner13-Jun-03 4:14
Chris Warner13-Jun-03 4:14 
GeneralNo Disk A:\ Annoyance Pin
claudus13-Apr-03 2:10
claudus13-Apr-03 2:10 
GeneralNo Disk A:\ Annoyance Pin
claudus13-Apr-03 2:08
claudus13-Apr-03 2:08 
GeneralYou can use the DirList and DriveList controls from VB6 Pin
TeaTime25-Feb-03 4:15
TeaTime25-Feb-03 4:15 
GeneralRe: You can use the DirList and DriveList controls from VB6 Pin
Chris Warner13-Jun-03 4:19
Chris Warner13-Jun-03 4:19 
QuestionHow about this... Pin
9-Mar-02 18:30
suss9-Mar-02 18:30 
AnswerRe: How about this... Pin
kaleid11-Mar-02 17:41
kaleid11-Mar-02 17:41 
AnswerRe: How about this... Pin
Sprudling19-Feb-03 6:10
Sprudling19-Feb-03 6:10 
Questionwhat about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
13-Feb-02 7:40
suss13-Feb-02 7:40 
AnswerRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
Ryan Farley17-Feb-02 5:38
Ryan Farley17-Feb-02 5:38 
GeneralRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
yannc17-Feb-02 8:08
yannc17-Feb-02 8:08 
GeneralRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
John McTainshz20-Aug-02 18:56
sussJohn McTainshz20-Aug-02 18:56 
GeneralRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
Ryan Farley20-Aug-02 19:09
Ryan Farley20-Aug-02 19:09 
GeneralRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
Chris Warner13-Jun-03 4:17
Chris Warner13-Jun-03 4:17 
GeneralRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
Peter Smartt14-Dec-03 17:50
Peter Smartt14-Dec-03 17:50 
AnswerRe: what about 'FolderNameEditor.FolderBrowser' - class in 'System.Windows.Forms.Design' Pin
Anonymous24-Mar-03 1:47
Anonymous24-Mar-03 1:47 
with this code i am getting an error that

"The type or namespace name 'FolderNameEditor' could not be found (are you missing a using directive or an assembly reference?)"

what should I do?Confused | :confused:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.