[c#] Accessing the target path of a shortcut (*.lnk)?

Caporegime
Joined
18 Oct 2002
Posts
29,493
Location
Back in East London
I've been banging my head on my desk for ten minutes. I'm simply trying to find the target path of a shortcut file. I have seen examples that read the .lnk as a binary and parse the data, but I'd rather hope there was a more standard, higher level way of doing this. In semi-pseudo I just want to be able to:
Code:
ShortcutFile file = new ShortcutFile("c:\dir\shortcut.lnk");
String target = file.TargetPath;
but it seems this is not the case.

I've looked around MSDN and google for sometime and the closest I got was Windows Scripting Object COM library (IWshRuntimeLibrary) but it spits the fallback COM error (the defacto "'unknown error' error")

Help?! :(
 
Using the IWshRuntimeLibrary works fine for me:
Code:
private void button1_Click(object sender, EventArgs e)
{
    string linkPathName = @"d:\Test.lnk";

    if (System.IO.File.Exists(linkPathName))
    {
        WshShell shell = new WshShell();
        IWshShortcut link = (IWshShortcut)shell.CreateShortcut(linkPathName);
        
        txtTarget.Text = link.TargetPath;
        txtWorkingDir.Text = link.WorkingDirectory;
    }
}
 
"Cannot create instance of the abstract class or interface 'IWshRuntimeLibrary.WshShell'"

Which version of the runtime are you using, if you don't mind me asking?
 
"Cannot create instance of the abstract class or interface 'IWshRuntimeLibrary.WshShell'"

...

You need a couple of extra steps to make Mickey's code work:

After creating your project, right-click on the project name within the Solution Explorer, select "Add Reference", select the "COM" tab, find and select the "Windows Script Host Object Model" in the listbox, click "Select", and then click "OK"

add the following to your file:

using IWshRuntimeLibrary;
 
I've got all those.. that particular error was because I have to use WshShellClass(), rather than WshShell() - which is why I asked the version.

I'm also accessing the file across the network.. so the filename is \\server\share\file.lnk format.
 
I'm on Vista 64 Ultimate, VS2008, .NET 3.5 SP1.

I've tested it in a windows forms app and an asp.net website, works perfectly for me.
 
and my head banging continues :/

Which version of the library is shown in the references dialogue window, if you don't mind? Mine is showing as 1.0.
 
Back
Top Bottom