I needed to make a shortcut file (.lnk file) from my CSharp application. As far as I know there is no way to do it directly from the .NET code. Only way is to use Windows API calls or Windows scripting capabilities. I decided to use scripting and here is how it gets done.
First, add a reference to COM-object 'Windows Script Host Object Model' from your project's properties. Secondly, import namespace 'IWshRuntimeLibrary' in your code. And here is the code itself:
private void MakeShortcut(string appDisplayName, string exeFullPath)
{
if (string.IsNullOrEmpty(appDisplayName) || string.IsNullOrEmpty(exeFullPath))
{
return; // Fail if name or path is missing
}
try
{
IWshShell_Class wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + appName + ".lnk")
as IWshRuntimeLibrary.IWshShortcut;
shortcut.Arguments = "";
shortcut.TargetPath = exeFullPath;
shortcut.WindowStyle = 1; // Normal window
shortcut.Description = "Shortcut to " + appName;
shortcut.WorkingDirectory = "";
shortcut.IconLocation = exeFullPath;
shortcut.Save();
}
catch
{
}
}
I wrote it as a procedure so the code can be easily copy/pasted to other projects as well.
The code above makes a shortcut to Desktop, so change ' Environment.SpecialFolder.Desktop' if you need your shortcut to some other place.
No comments:
Post a Comment