c# - 无法在 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
它是空的。
解决方案
我发现了问题。
这一行:System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");
我在文件名中添加了“.lnk”扩展名,但是当我用它搜索它时dir.Items().Item(shortcutName);
没有扩展名。
解决方法:写在函数开头shortcutName += ".lnk";
并得到这样的路径:System.IO.Path.Combine(shortcutPath, shortcutName);
推荐阅读
- google-sheets - 通过将其链接到另一个工作簿来从谷歌表格中删除条目的数组/列表
- python - Python TicTacToe 函数的时间复杂度
- java - 使用“config.xml”文件加载适配器
- python - PIP 和 Conda 有冲突吗?
- linux - 如何在我的 KDE Plasma 面板上放置不同 chrome 配置文件的图标?
- google-cloud-platform - 如何使我的 Cloud Function 只能从我的 GCP 服务帐户调用
- python - Selenium 网页抓取:如何将一个选项卡优先于另一个选项卡
- python - 逻辑测试未返回预期结果
- python - ImportError pyzbar macbook m1
- c - 在 c 中用 '' 或 "" 声明 char 变量的区别