UnauthorizedAccessException while creating a registry key
I am learning how to add a shortcut to Windows context menu to my application. I came across this article and I tried this. This is the code it uses to create a key in the registry.
private void btnAddMenu_Click(object sender, System.EventArgs e)
{
RegistryKey regmenu = null;
RegistryKey regcmd = null;
try
{
regmenu = Registry.ClassesRoot.CreateSubKey(MenuName);
if(regmenu != null)
regmenu.SetValue("",this.txtName.Text);
regcmd = Registry.ClassesRoot.CreateSubKey(Command);
if(regcmd != null)
regcmd.SetValue("",this.txtPath.Text);
}
catch(Exception ex)
{
MessageBox.Show(this,ex.ToString());
}
finally
{
if(regmenu != null)
regmenu.Close();
if(regcmd != null)
regcmd.Close();
}
}
The problem is that I run it through my admin account, it works fine. But when I do it through another account that doesn't have admin rights, it throws this exception.
system.unauthorizedaccessexception access to the registry key is denied
Now, if I were to use this code in one of my own applications to create a shortcut in the context menu, I cannot be sure that every user will run it as Administrator, right?
Is there a way in C # to elevate user privileges when creating a registry key?
If you know of any other way to add an item to the Windows context menu, I'll be interested in them too.
Thank.
source to share
You cannot escalate permissions as such (at least I would like to know about it, but not yet possible), but you need to start / run the application (embed in manifest). Please take a look at these entries ...
How do I get a .NET application running?
Programmatically enhanced process privileges?
I would advise what comments said by running this from a setup. Or let your application run as administrator from the beginning, or perhaps start an elevated process from your application - when needed (for example, start another exe from yours that has its manifest, correctly).
source to share