首页 > 解决方案 > 使用 C# 在 Windows 10 中查找 .lnk 快捷方式的目标

问题描述

我希望使用 C# 在 Windows 10 中找到快捷方式(.lnk 文件,而不是符号链接)的目标。

我已经搜索了几个小时并找到了许多方法来做到这一点,但我发现有两条评论令人难忘,Windows 10 中的快捷方式有些不同。另一个是它比听起来更棘手。我尝试过的方法都不起作用。我已经引用了所有必要的 COM 对象。

它们编译(完整的程序可以)但不产生任何输出,除了有权限错误的 Shell32 想法。

我尝试过的示例(片段)

        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(filePath);
        return shortcut.TargetPath;
        // supposed to reference an existing shortcut, but no output
        
        ---or---
                    
        dynamic shortcut;
        dynamic windowsShell;
        Type shellObjectType = Type.GetTypeFromProgID("WScript.Shell");
        windowsShell = Activator.CreateInstance(shellObjectType);
        shortcut = windowsShell.CreateShortcut(LinkName);
        string Properfile = shortcut.TargetPath;
        // Release the COM objects
        shortcut = null;
        windowsShell = null;
        return Properfile;
        //no output

        
        ---or---
        
        string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
        string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

        Shell shell = new Shell();
        Folder folder = shell.NameSpace(pathOnly);
        FolderItem folderItem = folder.ParseName(filenameOnly);
        if (folderItem != null)
        {
            Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
            return link.Path;
        }
        // permission error
        

它们是片段,但传达了输入、过程和结果的概念。

我发现的唯一其他线索是关于 .lnk 文件结构的 Microsoft 文档。我见过解析它们的解决方案(旧版本),但真的很想继续使用现代 API。

所以我总结了(是的,澳大利亚拼写)我想要什么,我尝试了什么以及代码是如何失败的。

从长远来看,目标是有一个快捷方式窗口,但似乎我需要返回可执行文件以在 ListView 中获取不同大小的图标。

标签: c#iconsshortcut

解决方案


已由Alexey回答:

将应用程序清单文件添加app.manifest到解决方案的启动项目(如果当前不存在)(右键单击项目 -> 添加 -> 新项目 -> 常规 -> 应用程序清单文件)。在你的app.manifest档案中,

替换这行代码:

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

有了这个:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

requireAdministrator使您的应用程序以管理员权限运行,从而为您提供所需的访问权限。


推荐阅读