I have a requirement for an application to "run on start-up" for all users. This has to be setup by the application it's self, not by a user adding a shortcut to start-up folder or something similar. I have managed to get this to work by adding the .exe path to the registry Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. The following code successfully adds the path to the registry when in debug mode and visual studios is run as administrator.
using Microsoft.Win32;
var path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
try
{
string baseDir = "EXAMPLE_DIR";
using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(path, true))
{
if (key is not null)
{
string exePath = $@"{baseDir}\iOK2.exe";
key.SetValue("iOK2", exePath);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
However the same code fails to add to the registry when it has been "Published" to an an executable (.exe) file.
The code doesn't produce any errors, it seemingly executes and exists successfully. I have tried running as admin, creating an app.manifest and requiring admin, ensured it's compiled to 64-bit and is accessing the correct registry Any ideas on what is happening or something I'm missing? If this fails I could potentially call a PowerShell script to edit the registry, but would rather keep dependencies to a minimum if at all possible