Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version

How to Browse for a Folder

, 16 Feb 2006
This article presents a 'cut-n-paste' solution for getting the path to a directory.
// GetFolder_Demo.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "shlobj.h"
#include <string>

bool GetFolder(std::string& folderpath, const char* szCaption = NULL, HWND hOwner = NULL)
{
	bool retVal = false;

	// The BROWSEINFO struct tells the shell 
	// how it should display the dialog.
	BROWSEINFO bi;
	memset(&bi, 0, sizeof(bi));

	bi.ulFlags   = BIF_USENEWUI;
	bi.hwndOwner = hOwner;
	bi.lpszTitle = szCaption;

	// must call this if using BIF_USENEWUI
	::OleInitialize(NULL);

	// Show the dialog and get the itemIDList for the selected folder.
	LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);

	if(pIDL != NULL)
	{
		// Create a buffer to store the path, then get the path.
		char buffer[_MAX_PATH] = {'\0'};
		if(::SHGetPathFromIDList(pIDL, buffer) != 0)
		{
			// Set the string value.
			folderpath = buffer;
			retVal = true;
		}		

		// free the item id list
		CoTaskMemFree(pIDL);
	}

	::OleUninitialize();

	return retVal;
}

int _tmain(int argc, _TCHAR* argv[])
{
	std::string szPath("");

	if (GetFolder(szPath, "Select a folder.") == true) 
	{
		printf("You selected: \"%s\".\n", szPath.c_str());
	}

	else
	{
		printf("No folder selected!\n");
	}
	
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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

About the Author

Nitron
Software Developer (Senior) Barbnet Investment Co.
United States United States
Walter Storm is currently a principal software engineer doing quantitative research for a private hedge fund. Originally from Tunkhannock, PA., he has a B.S. in Aerospace Engineering from Embry-Riddle Aeronautical University[^], and an M.S. in Systems Engineering from SMU[^]. He has been professionally developing software in some form or another since January of 2001.
 
View Walter Storm's profile on LinkedIn.[^]

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 16 Feb 2006
Article Copyright 2006 by Nitron
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid