5

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?

Eddie
  • 53,828
  • 22
  • 125
  • 145
Alan Mullett
  • 1,106
  • 13
  • 26

3 Answers3

1

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

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • 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 Mar 17 '09 at 08:08
  • 1
    Why don't you want to use COM? Usign IShellLink is the correct way to do things as that is the API that Windows provides for shortcut parsing/moditifcation. Your original code which used Windows Scripting Host wasn't the best way to do things but that was because it used a wrapper object designed for scripting languages, not because it used a COM object. COM is used behind the scenes all the time on Windows; it's unavoidable. – Leo Davidson Nov 22 '10 at 06:11
1

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

Sarel Botha
  • 12,419
  • 7
  • 54
  • 59
  • 1
    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 Mar 24 '09 at 10:01
0

I got interested in this as well a while ago.

Here is the accepted response with a link to a (informal) description of the format of LNK files. Apparently, all available methods yet go through some API.

Community
  • 1
  • 1
MPelletier
  • 16,256
  • 15
  • 86
  • 137