71

How do you create an application shortcut (.lnk file) in C# or using the .NET framework?

The result would be a .lnk file to the specified application or URL.

1

6 Answers 6

61

It's not as simple as I'd have liked, but there is a great class call ShellLink.cs at vbAccelerator

This code uses interop, but does not rely on WSH.

Using this class, the code to create the shortcut is:

private static void configStep_addShortcutToStartupGroup()
{
    using (ShellLink shortcut = new ShellLink())
    {
        shortcut.Target = Application.ExecutablePath;
        shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
        shortcut.Description = "My Shorcut Name Here";
        shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
        shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
    }
}
11
  • Anyone tried ShellLink on Vista? Looks like the code was written in 2003.
    – blak3r
    Commented Jun 24, 2009 at 1:25
  • 9
    Works on Windows 7 and even in 64-bit applications :)
    – fparadis2
    Commented Jul 19, 2011 at 14:25
  • 1
    @Ryan - Make sure you get the FileIcon.cs file as well.... the two files work hand and hand
    – DJ Burb
    Commented Mar 5, 2012 at 20:30
  • 1
    Maybe it's a stupid question, but how to add ShellLink to project? I've downloaded it and added to a new folder Libraries. But in the code using (ShellLink shortcut = new ShellLink()) it can't find ShellLink. Commented Apr 19, 2014 at 18:53
  • 3
    I'd just like to point out that this method has limitations in .NET I ended up having to use the other answer below which uses dynamics and WSH. The problem appears to be related to UAC: stackoverflow.com/questions/2934420/… So the issues is that the COM interface requires admin access, which your end users may not have. If you know they have access then it's not an issue. However, in cases where your users do not have admin access, the WSH with Dyanmics approach below works. Commented Oct 21, 2014 at 16:00
60

Nice and clean. (.NET 4.0)

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
dynamic shell = Activator.CreateInstance(t);
try{
    var lnk = shell.CreateShortcut("sc.lnk");
    try{
        lnk.TargetPath = @"C:\something";
        lnk.IconLocation = "shell32.dll, 1";
        lnk.Save();
    }finally{
        Marshal.FinalReleaseComObject(lnk);
    }
}finally{
    Marshal.FinalReleaseComObject(shell);
}

That's it, no additional code needed. CreateShortcut can even load shortcut from file, so properties like TargetPath return existing information. Shortcut object properties.

Also possible this way for versions of .NET unsupporting dynamic types. (.NET 3.5)

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
object shell = Activator.CreateInstance(t);
try{
    object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"});
    try{
        t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:\whatever"});
        t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"});
        t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
    }finally{
        Marshal.FinalReleaseComObject(lnk);
    }
}finally{
    Marshal.FinalReleaseComObject(shell);
}
7
  • 2
    Very clean. This would be the top answer if the question was asked again.
    – Damien
    Commented Jan 8, 2014 at 9:07
  • This will not be able to create a shortcut whose name has Unicode characters in it. Tested on Win7 with .NET 4.0. The COM object replaces the Unicode characters with question marks, which aren't valid in a file name. Commented Feb 21, 2014 at 21:54
  • Not a big deal, you can rename the file after .Save anyway, but thanks for notifying.
    – IS4
    Commented Feb 23, 2014 at 10:32
  • Thank you, I was searching a long time for this. More parameters can be found here: msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspx
    – Justin
    Commented Sep 8, 2014 at 9:40
  • 1
    @DaveCousineau System.__ComObject is the correct type, denoting a wrapper around a particular COM object. .NET is supposed to be able to use dynamic to query for IDispatch supported by the COM object and invoke its methods, but .NET Core did not implement it until .NET 5.
    – IS4
    Commented May 11, 2023 at 14:19
13

I found something like this:

private void appShortcutToDesktop(string linkName)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=file:///" + app);
        writer.WriteLine("IconIndex=0");
        string icon = app.Replace('\\', '/');
        writer.WriteLine("IconFile=" + icon);
        writer.Flush();
    }
}

Original code at sorrowman's article "url-link-to-desktop"

5
  • 12
    Given the choice between interop / wsh or reverse engineering the file format i would choose the latter. I think it is a pretty safe bet they won't change the format anytime soon. Commented Apr 6, 2011 at 13:29
  • 18
    Anuraj: You are cheating - this does not create a LNK but a URL file. Commented Aug 26, 2011 at 11:46
  • @HelgeKlein Its OK if you Registered your Application to use a URI Scheme Commented Jan 7, 2014 at 4:20
  • This is so simple. I don't care that it is a .url file instead of a .lnk assuming it ends up doing the same thing. Why wouldn't I use the simplest solution? I tested it for my purposes and it seems to work just fine. I find the only line that is really needed is "URL=" for my purposes. Commented Jun 3, 2015 at 20:57
  • Not working on Windows 10 x64:"The target "" of this Internet Shortcut is not valid ..." . I created internet link to a web resource and changed it to my exe path in Properties->Web Document->Url - it launche the app. Also, i've checked the format of windows created internet link and it is different (e.g. has some GUID field). Thus, this is not a valid format. P.S. It is better to use Uri and Uri.AbsoluteUri rather than strings in this case.
    – aderesh
    Commented Dec 16, 2016 at 20:02
1

After surveying all possibilities I found on SO I've settled on ShellLink:

//Create new shortcut
using (var shellShortcut = new ShellShortcut(newShortcutPath)
{
     Path = path
     WorkingDirectory = workingDir,
     Arguments = args,
     IconPath = iconPath,
     IconIndex = iconIndex,
     Description = description,
})
{
    shellShortcut.Save();
}

//Read existing shortcut
using (var shellShortcut = new ShellShortcut(existingShortcut))
{
    path = shellShortcut.Path;
    args = shellShortcut.Arguments;
    workingDir = shellShortcut.WorkingDirectory;
    ...
}

Apart of being simple and effective, the author (Mattias Sjögren, MS MVP) is some sort of COM/PInvoke/Interop guru, and perusing his code I believe it is more robust than the alternatives.

It should be mentioned that shortcut files can also be created by several commandline utilities (which in turn can be easily invoked from C#/.NET). I never tried any of them, but I'd start with NirCmd (NirSoft have SysInternals-like quality tools).

Unfortunately NirCmd can't parse shortcut files (only create them), but for that purpose TZWorks lp seems capable. It can even format its output as csv. lnk-parser looks good too (it can output both HTML and CSV).

4
  • 1
    Somewhat ironic given that link contains the text "webhost4life" but that ShellLink link is 404 :-(
    – noonand
    Commented Jan 26, 2015 at 12:09
  • @noonand indeed, and it seems the library wasn't cached on the Wayback Machine either. Fortunately I've kept a copy: onedrive.live.com/… Commented Jan 26, 2015 at 21:05
  • What is it with people posting code as a zip? I can't find a copy of this library anywhere on the internet :)
    – caesay
    Commented Apr 25, 2022 at 16:54
  • @caesay here it is in a git repo (of the project where I used it) :) sourceforge.net/p/tvgamelauncher/code/ci/master/tree/… Commented Apr 25, 2022 at 23:24
1

Donwload IWshRuntimeLibrary

You also need to import of COM library IWshRuntimeLibrary. Right click on your project -> add reference -> COM -> IWshRuntimeLibrary -> add and then use the following code snippet.

private void createShortcutOnDesktop(String executablePath)
{
    // Create a new instance of WshShellClass

    WshShell lib = new WshShellClass();
    // Create the shortcut

    IWshRuntimeLibrary.IWshShortcut MyShortcut;


    // Choose the path for the shortcut
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"\\AZ.lnk");


    // Where the shortcut should point to

    //MyShortcut.TargetPath = Application.ExecutablePath;
    MyShortcut.TargetPath = @executablePath;


    // Description for the shortcut

    MyShortcut.Description = "Launch AZ Client";

    StreamWriter writer = new StreamWriter(@"D:\AZ\logo.ico");
    Properties.Resources.system.Save(writer.BaseStream);
    writer.Flush();
    writer.Close();
    // Location for the shortcut's icon           

    MyShortcut.IconLocation = @"D:\AZ\logo.ico";


    // Create the shortcut at the given path

    MyShortcut.Save();

}
2
  • I don't have that COM library on my Windows 8 PC.
    – Damien
    Commented Jan 8, 2014 at 9:10
  • @Damien There is something called Google.. lolx :D just kidding dear you can download it from here. I am also updating my question. Thanks for pointing it out originaldll.com/file/interop.iwshruntimelibrary.dll/20842.html
    – AZ_
    Commented Jan 8, 2014 at 10:28
0

Similar to IllidanS4's answer, using the Windows Script Host proved the be the easiest solution for me (tested on Windows 8 64 bit).

However, rather than importing the COM type manually through code, it is easier to just add the COM type library as a reference. Choose References->Add Reference..., COM->Type Libraries and find and add "Windows Script Host Object Model".

This imports the namespace IWshRuntimeLibrary, from which you can access:

WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);
link.TargetPath=TargetPathName;
link.Save();

Credit goes to Jim Hollenhorst.

Not the answer you're looking for? Browse other questions tagged or ask your own question.