Search code examples
c#winapishortcut

Unable to create a shortcut in C#


In my program I want to give the user the ability to create a shortcut.

I tried using the IWshRuntimeLibrary, but it doesn't support Unicode character, and therefore fails.

I have found this answer, and it works when I copy it exactly like it is, but doesn't work when I put it in a function and use variables.

This is the code I use:

public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation, string description = "", string args = "")
{
    // Create empty .lnk file
    string path = System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");
    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(shortcutPath);
    Shell32.FolderItem itm = dir.Items().Item(shortcutName);
    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;
    // Set the .lnk file properties
    lnk.Path = targetFileLocation;
    lnk.Description = description;
    lnk.Arguments = args;
    lnk.WorkingDirectory = Path.GetDirectoryName(targetFileLocation);
    lnk.Save(path);
}

As you can see, it is the same exact code. The only difference is the use of variables instead of hard-coded values.

I call the function like so: Utils.CreateShortcut("Name", @"D:\Desktop", "notepad.exe", args: "Demo.txt");

And I get a System.NullReferenceException for the line Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink; because itm is null.


Solution

  • I have found the problem.

    This line: System.IO.Path.Combine(shortcutPath, $"{shortcutName}.lnk");

    I add the ".lnk" extension to the file name, but when I search for it with dir.Items().Item(shortcutName); it doesn't have the extension.

    The solution: Write at the beginning of the function shortcutName += ".lnk";

    And get the path like so: System.IO.Path.Combine(shortcutPath, shortcutName);