We have a network drive full of shortcuts (.lnk files) that point to folders and I need to traverse them programmatically in a C# Winforms app.
What practical options do I have?
How to open an LNK file. Opening an LNK file, by double-clicking it or right-clicking it and selecting Open, opens the file, folder, or program to which the LNK file points. Advanced users can edit an LNK file's properties by right-clicking the file and selecting Properties.
LNK files are user profile specific in that LNK files are recorded per user on the system. Windows generated LNK files are stored in the folder C:\Users\ <username>\AppData\Roaming\Microsoft\Windows\Recent.
In Microsoft operating system, LNK files are the shortcut file to point to an executable. These shortcut files are used as a direct link to an executable file. Manipulated. LNK file's possible actions include masquerade system process to execute malware, Download malicious files from the internet, Delivery of .
lnk are Windows shortcut files. These are just pointers in Windows that point to your original files. Dropbox can't follow these links, so you'll need to place the original files into your Dropbox folder in order to sync them.
Add IWshRuntimeLibrary as a reference to your project. Add Reference, COM tab, Windows Scripting Host Object Model.
Here is how I get the properties of a shortcut:
IWshRuntimeLibrary.IWshShell wsh = new IWshRuntimeLibrary.WshShellClass();
IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(filename);
The shortcut object "sc" has a TargetPath property.
If you do not wish to reference COM, and distribute the Interop.IWshRuntimeLibrary.dll with your product (remembering Jay Riggs "Embed Interop Types": False)
You can use the new dynamic COM instead.
private void Window_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
dynamic shortcut;
dynamic windowsShell;
try
{
var file = files[0];
if (Path.GetExtension(file)?.Equals(".lnk",StringComparison.OrdinalIgnoreCase) == true)
{
Type shellObjectType = Type.GetTypeFromProgID("WScript.Shell");
windowsShell = Activator.CreateInstance(shellObjectType);
shortcut = windowsShell.CreateShortcut(file);
file = shortcut.TargetPath;
// Release the COM objects
shortcut = null;
windowsShell = null;
}
//
// <use file>...
//
}
finally
{
// Release the COM objects
shortcut = null;
windowsShell = null;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With