Create shortcut with Unicode character

4

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)
c#
winapi
asked on Stack Overflow Nov 24, 2012 by Naresh • edited Nov 24, 2012 by kmatyaszek

1 Answer

6

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:\windows\system32\shell32.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:\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);
answered on Stack Overflow Nov 24, 2012 by Hans Passant • edited Jun 1, 2016 by Hans Passant

User contributions licensed under CC BY-SA 3.0