December 23rd, 2011

How do I get the full path for the target of a shortcut file?

A customer was having trouble obtaining information from a shortcut file. “Here is a sample program that tries to print the target of a shortcut file, but it only gets the file name without a directory. How do I get the full path?”

 IShellLink *psl;
 ... code that loads the IShellLink omitted ...
 TCHAR szPath[MAX_PATH];
 WIN32_FIND_DATA wfd;
 hr = psl->GetPath(szPath, MAX_PATH, &wfd, SLGP_UNCPATH);
 if (SUCCEEDED(hr)) {
  _tprintf(TEXT("Got path: %s\n"), wfd.cFileName);
 }

Recall that the WIN32_FIND_DATA structure contains only a file name in the cFile­Name member. It doesn’t have any path information. The WIN32_FIND_DATA structure was originally created for the Find­First­File function, and you already know the directory you are searching in because you passed it to Find­First­File.

But we’re not using the WIN32_FIND_DATA structure in conjunction with Find­First­File, so where do I get the directory from?

In the customer’s excitement over the WIN32_FIND_DATA structure, they forgot about that other parameter: szPath.

 if (SUCCEEDED(hr)) {
  _tprintf(TEXT("Got path: %s\n"), szPath);
 }

The answer was sitting right there in front of them, like an overlooked Christmas present.

(Don’t forget, the target of the shortcut might not be a file, in which case the call to Get­Path will return S_FALSE.)

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.