I am trying to programatically create a shortcut to a directory. I have found numerous examples, but none appear to work realiably.
I observe three different results in the produced shortcut's properties:
The Shortcut Type of File is assigned as "Shortcut(.lnk)" which cause the Open With dialog box to pop up asking me to attach an extension to it.
The Shortcut Type of File property is assigned as "File" which does absolutely nothing when double clicked.
Or lastly which is of course my favorite... the Shortcut Type of File property is assigned as: "File Folder" which works like it should.
Here is the code I am currently using... I've tried a few variations of this.
bool IsExists = false;
string icon = appPath + "Welcome.ico";
// Their is a difference to local and ClickOnce App locations... this compensates for it
IsExists = System.IO.File.Exists(icon);
if (!IsExists)
{
icon = appPath + @"bin\Debug\Welcome.ico";
}
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
var target = (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Artronix\Welcome To FreightWare Online\").Replace(@"\","/");
IWshShortcut shortcut;
var wshShell = new WshShellClass();
shortcut = (IWshShortcut)wshShell.CreateShortcut(Path.Combine(desktop, @"FreightWare Resources.lnk"));
shortcut.IconLocation = icon;
shortcut.TargetPath = Path.GetFullPath(target);
shortcut.Save();
Thank you everyone for your help... I figured it out. I didn't want to post it as an answer, but thought just in case someone else happened to come across this same problem... Although I feel sheepish about my oversight.
It turns out there was nothing wrong with the code. Panhandel gave me a clue to where to find the solution when he made the statement: " I only achieved the first result when the target path didn't exist." Since he was always getting the correct result and he only got the results I was getting when the directory did not exist... I realized the problem may be that I create the directory programatically in one line then in the next create the icon... I needed to give the system more time for the directory to be fully created
Try ShellLink:
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("%HOMEPATH%/Desktop/");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With