tags:

views:

234

answers:

3

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?

A: 

I don't believe ReadAllBytes induces the OS to follow the lnk to its target. I suspect, the OS has already resolved the lnk file (maybe when you browsed to the file in Windows Explorer).

logicnp
It is a advertised shortcut from another computer, so the link can never be resolved
Flores
+1  A: 

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:

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.Path;
}
Hans Passant
+1  A: 

Turns out the file was locked because it was copied from another machine (i'm using server 2008 r2) unlocking it returned the behavoir to expected.

Stupid me.

Flores