Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to follow a windows fileystem shortcuts programatically in C# without using COM?

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?

like image 992
Alan Mullett Avatar asked Nov 06 '22 21:11

Alan Mullett


1 Answers

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

like image 156
Powerlord Avatar answered Nov 12 '22 15:11

Powerlord