views:

364

answers:

2

Back in .NET 1.0 days I wrote a method to return the target of a shortcut on MS Windows. It did this through using an interop to the Windows Script Hosting Object Model and brute forced through the COM interface:

private FileInfo GetFileFromShortcut(FileInfo shortcut)
{
    FileInfo targetFile = null;

    try
    {
        IWshRuntimeLibrary.WshShell wShell = new IWshRuntimeLibrary.WshShellClass();
        IWshRuntimeLibrary.WshShortcut wShortcut = (IWshRuntimeLibrary.WshShortcut)wShell.CreateShortcut(shortcut.FullName);

        // if the file wasn't a shortcut then the TargetPath comes back empty
        string targetName = wShortcut.TargetPath;
        if (targetName.Length > 0)
        {
            targetFile = new FileInfo(targetName);
        }
    }
    catch (Exception)
    { // will return a null targetFile if anything goes wrong
    }

    return targetFile;
}

This still bugs me, and I was looking to replace this with something more elegant, but only if the replacement actually works at least as well. I still can't find a native C# way of finding the target of a shortcut. Is there one, or is this still the best way of doing this type of thing?

A: 

It looks like someone has written a class to manipulate shortcut files in C# called ShellLink, but it too uses COM.

R. Bemrose
Hiding the COM activity behind another layer wasn't really what I wanted to do - I want to publish this code into an open source project and didn't like the COM bashing part. But if there's no other way....
Alan Mullett
+1  A: 

Can't you just open the .lnk or .url file and parse it?

This talks about the same thing and shows what the files look like: http://www.programmingtalk.com/showthread.php?t=7335

sjbotha
I'm not sure that parsing a file that hasn't a published definition is something that I want to rely upon in my production code. There is a safe workaround which is bashing the COM interface at at least I know that will always work.
Alan Mullett