【问题标题】:Create shortcut with Unicode character使用 Unicode 字符创建快捷方式
【发布时间】:2012-11-24 14:11:35
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: c# winapi


    【解决方案1】:

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

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

    【讨论】:

    • 这件事奏效了,一个改变而不是从文件系统中引用 Shell32.dll,转到“添加引用...”对话框的 COM 选项卡并选择名为“Microsoft Shell Controls And Automation”的组件
    • 没有区别,浏览选项卡只是让查找文件更容易。
    • 但我认为添加 COM 组件使其独立于设备。并非所有用户都可以将 c:\ 作为他们的主磁盘。
    • 不,shell32.dll 是操作系统的一部分,可在每台机器上使用。就像 IWshRuntimeLibrary 提供程序一样。您也从未在代码中引用 c:\。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多