创建注册表项时出现UnauthorizedAccessException [英] UnauthorizedAccessException when creating a registry key

查看:67
本文介绍了创建注册表项时出现UnauthorizedAccessException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何在Windows上下文菜单中向应用程序添加快捷方式.我碰到了这篇文章然后我尝试了这是它用于在注册表中创建密钥的代码.

I'm researching on how to add a shortcut in the windows context menu to my application. I came across this article and I tried it out. 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 if I run it through my Administrator account, it works fine. But when I do it through a different account which doesn't have admin privileges, 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 can't be sure every user would run it as the Administrator, right?

在创建注册表项时,C#中是否有任何方法可以升级用户权限?

Is there any way in C# to escalate the user privileges when creating the registry key?

如果您知道将项目添加到Windows上下文菜单的任何其他方式,我也会对它们感兴趣.

If you know any other way to add an item to the windows context menu, I'd be interested in them too.

谢谢.

推荐答案

您不能像这样升级权限(至少我想了解一下,但目前尚不可能),但是您需要运行/启动您的应用程序(嵌入清单).
请看看这些条目...
如何强制我的.NET应用程序以管理员身份运行?
以编程方式提升流程特权?
我会建议您说些什么,然后从安装程序中运行.或者让您的应用从一开始就以管理员身份运行,或者在需要时(例如,运行您的另一个具有正确清单的exe文件)从您的应用中启动提升权限的进程.

You cannot escalate permissions as such (at least I'd like to know about it, but doesn't seem possible as yet), but you need to run / start your app (embed into manifest) elevated.
Please take a look at these entries...
How do I force my .NET application to run as administrator?
Elevating process privilege programatically?
I'd suggest what comments said, running that from the setup. Or let your app run as admin from the start, or possibly jump start an elevated process from your app - when needed (e.g. running another exe of yours that has its manifest properly).

这篇关于创建注册表项时出现UnauthorizedAccessException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆