How to list directories / files of a given path in your listbox easily?

19 06 2008

Assume you’ve a listbox and you want to fill all directories/files of a particular path to it. The usual method is iterate each file by FindFirstFile() and FindNextFile(), then add to listbox. Or any other cool tricks to do the same more easily?

You can use the api – DlgDirList(). It will populate the directories or files or drives to your listbox. You can select it by providing appropriate options. See the sample code snippet below, which lists all directories under C:\.

// The path Variable should be modifiable buffer.
// Since DlgDirList() returns data through it.
TCHAR Path[MAX_PATH] = _T("C:\\");
::DlgDirList( GetSafeHwnd(),
              Path, // in/out param.

For identifying directories, the DlgDirList() will decorate the directory name in format “[Directory]”. Now how to get the selected directory path from the listbox? Since its decorated, for that purpose, you can use function – DlgDirSelectEx(). It will undecorated the directory name and returns the real name. See the code snippet below.

// Read the selected directory from Listbox
TCHAR SelectedPath[MAX_PATH] = { 0 };
DlgDirSelectEx( GetSafeHwnd(),
                IDC_LIST1 );

Have a look at similar apis, such as DlgDirListComboBox(), DlgDirListComboBoxEx() etc. The name itself explains about it. Isn’t it? 😉

Targeted Audience – Intermediate.