Sunday, July 25, 2010

Create Desktop Shortcut

Shortcuts on the desktop are mostly just "normal" files with the extension ".lnk" (for link). To create such files with C# and to fill them with the right content is after my knowledge a little bit harder and only doable by including the COM object Windows Script Host Object Model.
Therefore in this post I want to show, how to create ".url" files instead of ".lnk" files - they have the same functionality, but are easier to create with .Net.
These files are mainly used to represent links on websites, but they can also be used to create file shortcuts.
The following function creates a shortcut in the path shortcutPath, here shortcutDest represents the path to the program which is to be linked and shortcutIcon the path to the icon, which should be used as symbol for the shortcut:

private void CreateShortcut(string shortcutPath, string shortcutDest, string shortcutIcon)
    StreamWriter sw = new StreamWriter(shortcutPath);
    sw.WriteLine("URL=file:///" + shortcutDest);
    sw.WriteLine("IconFile=" + shortcutIcon);

To create a shortcut on the desktop, you could call the function as follows:

CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\MyShortcut.url""C:\\Programme\\WinRAR\\WinRAR.exe""C:\\MyIcon.ico");

1 comment:

  1. Yea, try to pass an argument to that. Spoiler, it doesn't work.