'Is there a way in C# to find the current location of a shortcut target programatically?
Windows shortcuts use the Distributed Link Tracking service to get the current location of shortcut target which has moved or renamed when the link is clicked on. Is there any way of obtaining this location programmatically (in C#)?
Solution 1:[1]
Yes. You can use code from this blog article by Jani Järvinen:
class Program
{
[STAThread]
static void Main(string[] args)
{
const string shortcut = @"C:\test.lnk"; // Shortcut file name here
string pathOnly = System.IO.Path.GetDirectoryName(shortcut);
string filenameOnly = System.IO.Path.GetFileName(shortcut);
Shell32.Shell shell = new Shell32.Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
Console.WriteLine(link.Path);
}
Console.ReadKey();
}
}
Solution 2:[2]
A small addition to the code put up by Devil_coder /Cody Gray does what I need. Adding link.Resolve as shown below, with flags as defined in https://msdn.microsoft.com/en-us/library/windows/desktop/bb773996(v=vs.85).aspx makes link.Path return the current link target.
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
link.Resolve(5);
Console.WriteLine(link.Path);
Solution 3:[3]
It's easy, just use this lambda expression for getting target path or many other informations of shortcut.
public static string GetShortcutTargetFile(string shortcutFilename) => System.IO.File.Exists(shortcutFilename) ? ((IWshShortcut)new WshShell().CreateShortcut(shortcutFilename)).TargetPath : string.Empty;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cody Gray |
Solution 2 | SimonKravis |
Solution 3 | Har |