用Unicode字符创建快捷方式

6
我正在使用IWshRuntimeLibrary和C#创建快捷方式。快捷方式文件名是印地语“नमस्ते”。 以下是我用于创建快捷方式的代码,其中shortcutName = "नमस्ते.lnk"
 WshShellClass wshShell = new WshShellClass();
 IWshRuntimeLibrary.IWshShortcut shortcut;

shortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(destPath + "\\" + shortcutName);

 shortcut.TargetPath = sourcePath;
 shortcut.Save();

shortcut.Save()的操作中,我遇到了以下异常。
The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
1个回答

9
您可以通过调试器判断出问题所在。在调试器中检查“shortcut”,注意您的印地语名称已被替换为问号。这会生成无效文件名并触发异常。
您正在使用一种古老的脚本支持库,它无法处理该字符串。您需要使用更现代的工具。在“项目”+“添加引用”中,选择浏览选项卡并选择c:\windows\system32\shell32.dll。这将向您的项目添加Shell32命名空间,并提供一些与shell相关的接口。仅使用这些接口就足以让它正常运行,ShellLinkObject接口允许您修改.lnk文件的属性。只需要一个技巧,它没有从头创建新的.lnk文件的能力。您可以通过创建一个空的.lnk文件来解决此问题。这个方法很有效:
    string destPath = @"c:\temp";
    string shortcutName = @"नमस्ते.lnk";

    // Create empty .lnk file
    string path = System.IO.Path.Combine(destPath, shortcutName);
    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(destPath);
    Shell32.FolderItem itm = dir.Items().Item(shortcutName);
    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;
    // Set the .lnk file properties
    lnk.Path = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
    lnk.Description = "nobugz was here";
    lnk.Arguments = "sample.txt";
    lnk.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    lnk.Save(path);

2
这个东西起作用了,只需要一个更改,不要从文件系统引用Shell32.dll,而是进入“添加引用…”对话框的COM选项卡,选择组件名称为“Microsoft Shell Controls And Automation”。 - Naresh
没有什么区别,浏览选项卡只是让查找文件更容易一些。 - Hans Passant
但我认为添加COM组件可以使其独立于设备。并非所有用户都将c:\作为其主要磁盘。 - Naresh
1
不,shell32.dll是操作系统的一部分,并且在每台计算机上都可用。就像IWshRuntimeLibrary提供程序一样。您的代码中也永远不会引用c:\。 - Hans Passant
@HansPassant如果destPath不存在该怎么办?砰!行:System.IO.File.WriteAllBytes(path, new byte[0]);将失败并显示System.IO.DirectoryNotFoundException。因此,在那一行之前,我建议:if (!System.IO.Directory.Exists(destPath)) System.IO.Directory.CreateDirectory(destPath); - Simple
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接