Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been looking for a simple way to create a shortcut to a file in C#, but I've only found external dlls that do that. It's actually quite surprising, there's no built in way to do that..

Anyway, I know that lnk files are just text files with a certain command and a given path. I thought that maybe I could create a text file (in the code) set it's text to the right command and change it's extension to .lnk I've tried to do that manually first, but failed to do so.

Is there a way to do something like that (or maybe another simple way) to create a shortcut to a certain path in c#?

Just to be clear, by Shortcut I mean an .lnk file that leads to the file Edit: And by file I mean any file I'd want, not only a shortcut to my own application


I'll edit if it doesn't work well for every scenario.

Add these references:

  1. Microsoft Shell Controls And Automation
  2. Windows Script Host Object Model

Add this namespaces:

using Shell32;
using IWshRuntimeLibrary;

Next appears to be working:

var wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\shorcut2.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.TargetPath = @"C:UsersiminDesktopest folder";            
shortcut.Save();

Hope it helps others as well, thanks for your attention.

Also, if there IS a way to create a file, write the right commands and then change it to an lnk file, please let me know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
713 views
Welcome To Ask or Share your Answers For Others

1 Answer

One way to do this is pointed out by Joepro in their answer here:

You'll need to add a COM reference to Windows Scripting Host. As far as i know, there is no native .net way to do this.

WshShellClass wsh = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\shorcut.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.Arguments = "";
shortcut.TargetPath = "c:\app\myftp.exe";
// not sure about what this is for
shortcut.WindowStyle = 1; 
shortcut.Description = "my shortcut description";
shortcut.WorkingDirectory = "c:\app";
shortcut.IconLocation = "specify icon location";
shortcut.Save();

For .Net 4.0 and above, replace the first line with the following:

 WshShell wsh = new WshShell();

EDIT: This link can help too


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...