首页 > 解决方案 > 无法在 C# 中创建快捷方式

问题描述

在我的程序中,我想让用户能够创建快捷方式。

我尝试使用IWshRuntimeLibrary,但它不支持 Unicode 字符,因此失败了。

我找到了这个答案,当我完全复制它时它可以工作,但是当我将它放入函数并使用变量时它不起作用。

这是我使用的代码:

public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation, string description = "", string args = "")
{
    // Create empty .lnk file
    string path = System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");
    System.IO.File.WriteAllBytes(path, new byte[0]);
    // Create a ShellLinkObject that references the .lnk file
    Shell32.Shell shl = new Shell32.Shell();
    Shell32.Folder dir = shl.NameSpace(shortcutPath);
    Shell32.FolderItem itm = dir.Items().Item(shortcutName);
    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;
    // Set the .lnk file properties
    lnk.Path = targetFileLocation;
    lnk.Description = description;
    lnk.Arguments = args;
    lnk.WorkingDirectory = Path.GetDirectoryName(targetFileLocation);
    lnk.Save(path);
}

如您所见,它是完全相同的代码。唯一的区别是使用变量而不是硬编码值。

我这样调用函数:Utils.CreateShortcut("Name", @"D:\Desktop", "notepad.exe", args: "Demo.txt");

我得到了一条System.NullReferenceException线Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;,因为itm它是空的。

标签: c#winapishortcut

解决方案


我发现了问题。

这一行:System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");

我在文件名中添加了“.lnk”扩展名,但是当我用它搜索它时dir.Items().Item(shortcutName);没有扩展名。

解决方法:写在函数开头shortcutName += ".lnk";

并得到这样的路径:System.IO.Path.Combine(shortcutPath, shortcutName);


推荐阅读