在我的程序中,我想赋予用户创建快捷方式的能力。
我尝试使用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
为null。
我发现了问题。
这行: System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");
我在文件名中添加了“ .lnk”扩展名,但是当我用dir.Items().Item(shortcutName);
它搜索时没有扩展名。
解决方案:在函数的开头写 shortcutName += ".lnk";
并获得如下路径: System.IO.Path.Combine(shortcutPath, shortcutName);