c#securityexception不允许所请求的注册表访问权

开机自启动程序如下:

if (!System.IO.File.Exists(filename))
                    throw new Exception("该文件不存在!");
                string name = filename.Substring(filename.LastIndexOf("\\") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                {
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                if (isAutoRun)
                    reg.SetValue(name, filename);
                else
                    reg.SetValue(name, false);

然后弹出异常:securityexception不允许所请求的注册表访问权。

 

找了好久都说什么权限不够,不是我需要的答案。解决方法如下:

1、右键生成的exe应用程序,以管理员身份运行,如果没问题,就说明是可以访问修改注册表的;

但是这样是不能用的,因为你重启后会直接弹出异常,说不允许所请求的注册表访问权 。问题还是没解决。

 

2、一般在win7下,VS访问注册表HKEY_LOCAL_MACHINE,即程序中的LocalMachine是需要管理员身份运行的。但是访问HKEY_CURRENT_USER是没问题的。

所以修改程序如下:

...

reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                {
                    reg = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }

...

 

OK,可以了

c#securityexception不允许所请求的注册表访问权

上一篇:[AWS DA] API Gateway and Lambda Stage variable


下一篇:【c#概念】Marshal.SizeOf 方法、Marshal.AllocHGlobal 方法、IntPtr 结构