C# 无法在C中创建快捷方式#

C# 无法在C中创建快捷方式#,c#,winapi,shortcut,C#,Winapi,Shortcut,在我的程序中,我想让用户能够创建快捷方式 我尝试使用iwruntimelibrary,但它不支持Unicode字符,因此失败 我已经发现,当我复制它时,它可以正常工作,但当我把它放在函数中并使用变量时,它就不起作用了 这是我使用的代码: public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation, string description = "&

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

我尝试使用
iwruntimelibrary
,但它不支持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”)


我得到了行
Shell32.ShellLinkObject lnk=(Shell32.ShellLinkObject)itm.GetLink的
System.NullReferenceException
itm
为空。

我发现了问题

此行:
System.IO.Path.Combine(shortcutPath,$“{shortcutName}.lnk”)

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

解决方案:在函数的开头写入
shortcutName+=“.lnk”


然后像这样得到路径:
System.IO.path.Combine(shortcutPath,shortcutName)

我没有投反对票,但是可以找到应该投反对票的可能原因-将鼠标悬停在任何问题的“反对票”按钮上,最常见原因的摘要就会出现。还有更多信息,请访问。当然,这并不能阻止人们错误地使用该功能,但群众的智慧通常会占上风——如果一个人错误地使用它,那么另一个人通常会投赞成票来补偿。无论如何,你有没有试过找出为什么
itm
在你的版本中为空?你做了什么调试?谢谢你的反对意见我不知道。我试着用硬编码的值来代替变量,这是可行的,我找不到任何理由认为切换到变量会破坏代码。字符串是相等的,路径是有效的。谢谢编辑…但是如果你找到了解决方案,它应该在答案部分,而不是问题中!如果人们觉得有用的话,他们可以投票表决。我已经回滚了你的编辑。在这个问题上添加解决方案是不合适的。如果您找到了一个解决方案并想与他人分享,请在下面提供的空白处写下答案。看见