0

I've used C# and Powershell to create shortcuts, but when they are created in code they do not work. I click on the shortcut, the cursor shows the PC is thinking for a second and then nothing happens. This is the Powershell code I was using:

$currPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$tgtPath = ($currPath + "\bin\MyApp.exe")
$scutPath = ([Environment]::GetFolderPath("Desktop") + "\MyApp.lnk")
$wShell = New-Object -ComObject WScript.Shell
$scut = $wShell.CreateShortcut($scutPath)
$scut.TargetPath = $tgtPath
$scut.Save()

The C# code does essentially the same think using the IWshRuntimeLibrary. This little script basically just creates a shortcut on someone's desktop after they have downloaded my little standalone executable. I can manually create the shortcut and everything works fine. Why can't I do it through code?

I have created a few shortcuts and .url files on the desktop with the same name in the course of my testing, I'm not sure if that matters.

4
  • 1
    Right click the shortcut made programmatically and compare the "Target" and "Start In" fields to your manually made one that works.
    – Quantic
    Commented Dec 21, 2016 at 22:23
  • Possible duplicate of Creating a file shortcut (.lnk) Commented Dec 21, 2016 at 22:24
  • Try the solution provided in the above link. (and keep in mind the note regarding .NET 4.0 reference of WshShell vs WshShellClass. The solution is for c#. Commented Dec 21, 2016 at 22:26
  • @Quantic - That is exactly right. I did compare the properties carefully before, but I overlooked the start in field. Put this as the answer and I can accept it. The property that needs to be set is the WorkingDirectory of the shortcut object.
    – Ian
    Commented Dec 21, 2016 at 22:32

1 Answer 1

1

You often have to ensure the WorkingDirectory is assigned or else your program's Environment.CurrentDirectory will inherit the directory you called the shortcut from. Your program is likely closing due to not finding a resource by using a relative path, such as an icon: _notifyIcon.Icon = new System.Drawing.Icon(@"Resources\Icons\myicon.ico"); will crash when using a shortcut with a blank WorkingDirectory when the shortcut is launched from a process with a different working directory than where your .exe resides (e.g., the Explorer process that reads your shortcut and launches your program when you double click a shortcut).

You can test what a relative path expands to by using Path.GetFullPath(string relativePath), and you can see the current directory with Environment.CurrentDirectory. Launching a shortcut from the desktop with no Start In set I see the working directory as my desktop, meaning @"Resources\Icons\myicon.ico" will be expanded to @"C:\Users\me\Desktop\Resources\Icons\myicon.ico which is no good as the icon is somewhere else like @"C:\Program Files\MyProgram\Resources\Icons\myicon.ico".

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