Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - Create shortcut with Unicode character

I'm using IWshRuntimeLibrary to create shortcut with c#. the shortcut file name is in Hindi "??????".

I'm using following code my snip to create shortcut, where shortcutName = "??????.lnk"

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

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

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

on shortcut.Save() I'm getting following exception.

The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can tell what goes wrong with the debugger. Inspect "shortcut" in the debugger and note that your Hindi name has been replaced by question marks. Which produces an invalid filename and triggers the exception.

You are using an ancient scripting support library that's just not capable of handling the string. You'll need to use something more up-to-date. Project + Add Reference, Browse tab and select c:windowssystem32shell32.dll. That adds the Shell32 namespace to your project with a few interfaces to do shell related work. Just enough to get this going, the ShellLinkObject interface lets you modify properties of a .lnk file. One trick is needed, it doesn't have the ability to create a new .lnk file from scratch. You solve that by creating an empty .lnk file. This worked well:

    string destPath = @"c:emp";
    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) + @"
otepad.exe";
    lnk.Description = "nobugz was here";
    lnk.Arguments = "sample.txt";
    lnk.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    lnk.Save(path);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...