开发者

.NET read binary contents of .lnk file

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 an开发者_开发问答d 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?


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;
}


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜