Use special folder CSIDLs as the default location for user created files

Use special folder CSIDLs as the default location for user created files

Benefits

Description

Backing up a user’s work and having that work roam with the user are important features to many system administrators. By writing user’s files to the appropriate special folder CSIDL by default, your program will instantly be able to take advantage of IntelliMirror’s roaming user features and you’ll always write the files to the location the administrator has chosen.

By using the Win32 API SHGetFolderPath combined with CSIDL_PERSONAL as the default for new documents, your program will always get the preferred location to place files.

You should of course, allow the user to save files to permitted locations other than default folder, but by getting the default path from SHGetFolderPath before you display a save dialog, you’ll at least nudge the user in the right direction.

Try not to save document paths, but if you must, remember to always store it as a UNC, or preferably as a path relative to the CSIDL location you are dependent upon

Code Sample

In this sample we’re going to present the File Open common dialog. It’s important we set the starting path to correct folder for the user. To find the correct folder we use SHGetFolderPath to find the path for CSIDL_PERSONAL. We then set the dialog’s starting path to the path we just looked up.

LPTSTR  lpstrPath = NULL;
TCHAR   tszTempPath[_MAX_PATH];

if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL | CSIDL_CREATE, NULL, 
              SHGFP_TYPE_CURRENT, tszTempPath))
{
    // We got the path for CSIDL_PERSONAL
    lpstrPath = tszTempPath;
}

// lpstrPath now either points to the path returned from SHGetFolderPath
// or is still NULL.  NULL will load the default path for the platform.

// No do the file open dialog
CString     strFilter = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||";
CFileDialog dlgFile(TRUE, _T("*.txt"), NULL, OFN_FILEMUSTEXIST, strFilter,
                    this);
int         nReturn = NULL;

dlgFile.m_ofn.lpstrInitialDir = lpstrPath;

nReturn = dlgFile.DoModal();

Considerations

System support for SHGetFolderPath is not native on Windows 98, Windows 95, and Windows NT 4.0. These downlevel clients will require the installation of new system files prior to use. (Redistribution specifics not available at press time)

See Also

CSIDLs, SHGetFolderPath, UNC