How do I programmatically add a folder to my Documents library?

Raymond Chen

Today’s Little Program adds a folder to the Documents library. Remember that Little Programs do little to no error checking.

Today’s smart pointer library is… (rolls dice)… nothing! We’re going with raw pointers.

#define STRICT
#include <windows.h>
#include <ole2.h>
#include <shlobj.h>

int __cdecl wmain(int argc, wchar_t** argv)
{
  CoInitialize(nullptr);
  IShellLibrary* library;
  SHLoadLibraryFromKnownFolder(FOLDERID_DocumentsLibrary,
                               STGM_READWRITE, IID_PPV_ARGS(&library));
  for (int i = 1; i < argc; i++) {
    SHAddFolderPathToLibrary(library, argv[i]);
  }
  library->Release();
  CoUninitialize();
  return 0;
}

This program uses some helper functions for manipulating libraries. The SH­Load­Library­From­Known­Folder function is a shorthand for Co­Create­Instance(CLSID_Shell­Library) followed by IShell­Library::Load­Library­From­Known­Folder, and the SH­Add­Folder­Path­To­Library function is a shorthand for SH­Create­Item­From­Parsing­Name followed by IShell­Library::Add­Folder.

Run this program with the full path (or paths) to the folders you want to add to the Documents Library, and… nothing happens.

Ah, because there’s a gotcha with libraries: After you make a change to a library, you need to commit your changes. So let’s fix that:

#define STRICT
#include <windows.h>
#include <ole2.h>
#include <shlobj.h>

int __cdecl wmain(int argc, wchar_t** argv)
{
  CoInitialize(nullptr);
  IShellLibrary* library;
  SHLoadLibraryFromKnownFolder(FOLDERID_DocumentsLibrary,
                               STGM_READWRITE, IID_PPV_ARGS(&library));
  for (int i = 1; i < argc; i++) {
    SHAddFolderPathToLibrary(library, argv[i]);
  }
  library->Commit(); // add this line
  library->Release();
  CoUninitialize();
  return 0;
}

Okay, let’s try it again. Run this program with the full path (or paths) to the folders you want to add to the Documents Library, and hooray! the folders are added to the Documents Library.

0 comments

Discussion is closed.

Feedback usabilla icon