This code:
RegistryKey rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rKey.DeleteValue(Application.ProductName, false);
rKey.SetValue(Application.ProductName, Application.ExecutablePath, RegistryValueKind.String);
doesn't work on Windows 8. I don't have idea why because on Windows 7 and on Windows XP this solution works.
Can you help me?
In order to set something in the registry you need to run the application as an administrator.
To do so you first add a Application Manifest File
to the Properties "folder" in the project.
Then you change
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
To:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Then I don't know if the way you get the current executable path is correct, for me this have worked at least:
class Program
{
private static void RegisterAsRun()
{
string exePath = new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath;
Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", "TestApp", exePath, RegistryValueKind.String);
}
static void Main(string[] args)
{
RegisterAsRun();
Console.WriteLine("Hello!");
Console.ReadLine();
}
}
Another note is that if the application is compiled in x86 and the OS is x64 the registry key will end up in the Wow64 registry which makes it the following path:
HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run