Browse for folders using Shell32.dll's BrowseForFolder method in C#

To browse for a folder in .NET you can use the OpenFileDialog but if you want to limit your users to browsing to a folder instead of a file you can use the BrowseForFolder method from the ShellClass class in Shell32.dll. This is similar to my DirectoryBrowser VB6 sample.

First you need to set a reference to the Shell32.dll in your .NET project. In Solution Explorer right click the References entry, select Add New... and browse to the System32 folder and select Shell32.dll.

Then add the following C# code:

    string strPath;
    string strCaption = "Select a directory.";
    DialogResult dlgResult;

    Shell32.ShellClass shl = new Shell32.ShellClass();
    Shell32.Folder2 fld = (Shell32.Folder2)shl.BrowseForFolder(0, strCaption, 0, 

    if (fld == null)
        dlgResult =  DialogResult.Cancel;
        strPath = fld.Self.Path;
        dlgResult = DialogResult.OK;

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2024 TheScarms
Goto top of page