November 7th, 2016

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

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.