I wish to find the target of a shortcut (.lnk file, not a symlink) in Windows 10 using C#.
I have searched for hours and found numerous methods for doing this, but two comments I found are memorable, that shortcuts in Windows 10 are somewhat different. The other is that it's trickier than it sounds. None of the methods I have tried work. I've referenced all the necessary COM objects.
They compile (the full programs do) but produce no output, with the exception of the Shell32 idea that has a permission error.
Examples of what I've tried (snippets)
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(filePath);
return shortcut.TargetPath;
// supposed to reference an existing shortcut, but no output
---or---
dynamic shortcut;
dynamic windowsShell;
Type shellObjectType = Type.GetTypeFromProgID("WScript.Shell");
windowsShell = Activator.CreateInstance(shellObjectType);
shortcut = windowsShell.CreateShortcut(LinkName);
string Properfile = shortcut.TargetPath;
// Release the COM objects
shortcut = null;
windowsShell = null;
return Properfile;
//no output
---or---
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
// permission error
They're snippets but convey the idea of input, procedure and result.
The only other lead I found was to a Microsoft document on the structure of a .lnk file. I've seen solutions that parse them (older versions) but would really like to stay with a modern API.
So I summarised (yep, Aus spelling) what I want, what I've tried and how the code failed.
To put in perspective, the goal is to have a window of shortcuts, but it seems I need to go back to the executable to get different sized icons in a ListView.