Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# programmatically creating shortcut to directory does not always work

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:

  1. 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.

  2. The Shortcut Type of File property is assigned as "File" which does absolutely nothing when double clicked.

  3. 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();
like image 466
Anthony Griggs Avatar asked Jun 05 '13 21:06

Anthony Griggs


2 Answers

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

like image 190
Anthony Griggs Avatar answered Oct 18 '22 11:10

Anthony Griggs


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/");
}
like image 25
Kauê Gimenes Avatar answered Oct 18 '22 10:10

Kauê Gimenes