Introduction

In Windows, file shortcuts can be identified by the file extension. Default file extension for file and folder shortcuts is ".lnk". But also ".appref-ms" is used as a file extension for file shortcuts. Furthermore, it could be possible that installed applications use the default shortcut file extension for its own application dependent files. So using file extensions as evidence for shortcut is not sufficient.



Description

To check if a file is a shortcut and to resolve a shortcut path, the COM Library Microsoft Shell Controls And Automation is used. This library is added to the References of the Visual Studio project.

The library Microsoft Shell Controls And Automation provides an interop connection to Shell32. It provides access to Shell and Folder objects representing the file system.

Shell object, Folder object, and FolderItem object are used to check if a given file is a shortcut.

bool IsShortcut(string path)
{
  string directory = Path.GetDirectoryName(path);
  string file = Path.GetFileName(path);
  
  Shell32.Shell shell = new Shell32.Shell();
  Shell32.Folder folder = shell.NameSpace(directory);
  Shell32.FolderItem folderItem = folder.ParseName(file);
  
  if(folderItem != null)
  {
    return folderItem.IsLink;
  }
  
  return false;
}

Shell object, Folder object, FolderItem object, and ShellLinkObject object are used to resolve the file path of a given shortcut file.

string ResolveShortcut(string path)
{
  string directory = Path.GetDirectoryName(path);
  string file = Path.GetFileName(path);
  
  Shell32.Shell shell = new Shell32.Shell();
  Shell32.Folder folder = shell.NameSpace(directory);
  Shell32.FolderItem folderItem = folder.ParseName(file);
  
  Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  
  return link.Path;
}



References