C# tip: reading a shortcut's target
Posted: (EET/GMT+2)
In the C# newsgroups somebody asked how to read the target of a Windows shortcut programmatically. That is, he wanted to get the name of the application/file a shortcut (.LNK file) points to. Here's the solution.
But first some background. Shortcuts (or "shell links" as they are also called) can be manipulated using the COM objects in SHELL32.DLL, and there exists the IShellLink interface and the ShellLinkObject object, the latter of which is very useful. If you are using Visual Studio, you can simply add a reference to the COM library "Microsoft Shell Control And Automation" or to SHELL32.DLL directly, and then use the following code:
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link =
(Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return ""; // not found
}
Then, just call the code like this:
private void button1_Click(object sender, EventArgs e)
{
string shortcut = "C:\\Shortcut to notepad.exe.lnk";
MessageBox.Show(GetShortcutTargetFile(shortcut));
}
One of the reasons I wanted to share this solution here also is that I found it difficult to find simple enough code to do the job. Most code I found defined the IPersistFile and IShellLink interfaces themselves, which I find somewhat ugly, especially all that is needed is a "quick and simple" solution like the original poster.