Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET read binary contents of .lnk file

Tags:

c#

.net

shortcut

I want to read the binary contents of a .lnk file. As long as the target of the shortcut (lnk file) exists this works fine with IO.File.ReadAllBytes(string file).

BUT

If the target of the shortcut does not exist (believe me I want this) the method only returns zero's. I guess this is because the OS follows the link and if it does not exist it returns zero's

Is there some way to bypass the fact that the framework follows the target of the .lnk before displaying the contents of the .lnk file?

like image 570
Flores Avatar asked Apr 02 '10 09:04

Flores


People also ask

How do I view the contents of an LNK file?

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.

Are LNK files executable?

LNK is a filename extension for shortcuts to local files in Windows. LNK file shortcuts provide quick access to executable files (.exe) without the users navigating the program's full path.

How do I change LNK to default?

Open regedit from the Start Menu (You can also invoke the file using Run command). Click on the arrow to expand it and delete the sub-key named UserChoice . Exit from Registry Editor. After this do a reboot.


1 Answers

It doesn't make a lot of sense, don't have an easy way to check it. I reckon the best approach is to read the .lnk file the way it is supposed to be read. You can use COM to do so, the ShellLinkObject class implements the IShellLink interface. Get started with Project + Add Reference, Browse tab and navigate to c:\windows\system32\shell32.dll. That generates an interop library. Write code like this:

public static string GetLnkTarget(string lnkPath) {
    var shl = new Shell32.Shell();         // Move this to class scope
    lnkPath = System.IO.Path.GetFullPath(lnkPath);
    var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
    var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
    var lnk = (Shell32.ShellLinkObject)itm.GetLink;
    return lnk.Target.Path;
}
like image 94
Hans Passant Avatar answered Sep 16 '22 15:09

Hans Passant