.NET read binary contents of .lnk file

倖福魔咒の 提交于 2019-12-17 16:46:13

问题


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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2565885/net-read-binary-contents-of-lnk-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!