使用 Unicode 字符创建快捷方式

Nar*_*esh 4 c# winapi

我正在使用 IWshRuntimeLibrary 用 C# 创建快捷方式。快捷方式文件名是印地语“??????”。

我正在使用以下代码我的片段来创建快捷方式,其中 shortcutName = "??????.lnk"

 WshShellClass wshShell = new WshShellClass();
 IWshRuntimeLibrary.IWshShortcut shortcut;

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

 shortcut.TargetPath = sourcePath;
 shortcut.Save();
Run Code Online (Sandbox Code Playgroud)

shortcut.Save()我得到以下异常。

The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

您可以判断调试器出了什么问题。检查调试器中的“快捷方式”并注意您的印地语名称已被问号替换。这会产生无效的文件名并触发异常。

您正在使用一个古老的脚本支持库,它无法处理字符串。你需要使用更新的东西。项目 + 添加引用,浏览选项卡并选择 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);
Run Code Online (Sandbox Code Playgroud)

  • 这件事起作用了,只需进行一项更改,而不是从文件系统引用 Shell32.dll,转到“添加引用...”对话框的 COM 选项卡,然后选择名为“Microsoft Shell Controls And Automation”的组件 (2认同)