I want to add my WPF Application to run automatically on User Login only Once. So, I am using the following code on Application Startup
public void SetStartUpRegistry()
{
RegistryKey registryKeys = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows \\CurrentVersion\\RunOnce");
string[] appKeyNames = registryKeys.GetSubKeyNames();
var v = from x in appKeyNames
where appKeyNames.Contains("KeyName")
select x;
if (v.Count() == 0)
{
RegistryKey regkey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce", true);
string startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs)
+ @"\CompanyName\AppName.appref-ms";
regkey.SetValue("KeyName", "\"" + startPath + "\"");
}
}
This code run perfectly when I run it in VS but when I run it from exe or I deploy it using ClickOnce it throws exception on regkey.SetValue line "attempted to perform an unauthorized operation".
I can even create new subkey in this Registry Key replacing regkey.setValue with regKey.CreateSubKey method. So, I guess it can't be Access Permission issue.
I have complete rights on registry files, I even tried it with administrator account.
What can be the Problem with this code?
I thought Registry.CurrentUser can be accessed by user without any administrative privileges.
The code runs properly if I use Run rather than RunOnce, but I want to use RunOnce.