Create shortcut programmatically in C#
In cases where we need to create a shortcut for our application or for any other reason, the Windows Script Host Object Model
library allows us to do just that.
In order to access the classes that will enable us to create shortcuts we need to add the Windows Script Host Object Model
library as a reference to our project first.
- Right click on your project
- Click “Add Reference…”
- Select the “COM” tab on the left
- Search for Windows Script Host Object Model and add it as a reference
After you successfully add the reference in your project you should be able to use the snippet bellow to create shortcuts as you please.
Create shortcut:
1 2 3 4 5 6 7 8 9 10 11 | public static void CreateShortcut(string shortcutName, string shortcutPath, string targetFileLocation) { string shortcutLocation = System.IO.Path.Combine(shortcutPath, shortcutName + ".lnk"); WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutLocation); shortcut.Description = "My shortcut description"; // The description of the shortcut shortcut.IconLocation = @"c:\myicon.ico"; // The icon of the shortcut shortcut.TargetPath = targetFileLocation; // The path of the file that will launch when the shortcut is run shortcut.Save(); // Save the shortcut } |
Usage:
1 | CreateShortcut("my shortcut", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Assembly.GetExecutingAssembly().Location); |
erro System.IO.Path.Combine(shortcutPath, shortcutName + “.lnk”);
could not found
Also set property working directory(as below)
shortcut.WorkingDirectory = rootPath;
Otherwise the relative path used in application will get failed
This works!
Sadly though it only seems to create it for the current user…the moment I switch users it does not display the shortcut :(
That is where Environment.SpecialFolder.Desktop points to. If you want to target all users desktop then you will need to use Environment.SpecialFolder.CommonDesktopDirectory (requires .NET 4 or higher).
If you are using an older version of the .NET framework you will probably need to find another method if retrieving the desktop path, probably with the use of SHGetFolderPath.