2

I'm trying to combine two questions here: 1) How to create a relative shortcut in Windows and 2) How to create a Windows shortcut in C#

I have the following code to create shortcuts (based on the questions I've seen), but it throws an exception when assigning shortcut.TargetPath: "Value does not fall within the expected range"

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe /c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "";
    shortcut.Save();
}

How do I fix this and create my relative shortcut?

NB: I don't want to have to write a batch script to do this as my software will most likely be installed on PCs where the user does not have access to a command line - our clients often have very locked-down machines and will almost certainly not have the right permissions to run batch files. If you do have any suggestions as to how I might create a 'portable' folder (with my .exe in a subfolder) where the user only has to double-click something in the top level folder to run the exe, I am open to suggestions!

penny
  • 385
  • 5
  • 18

1 Answers1

5

You can't put arguments in the TargetPath-property. (see MSDN)

Put them into the Arguments- property:

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "/c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "P:\ath\to\any\icon.ico";
    shortcut.Save();
}
MatSnow
  • 7,357
  • 3
  • 19
  • 31