简体   繁体   English

使用C#代码在Windows 7中读取/写入注册表

[英]Registry read/write in windows 7 using c# code

I have a windows C# application which when user runs it i want to save the current time as login time in some registry and also when he close it as logout time.When i tried, it gives me requested registry access is not allowed exception.I have tried giving permission to that registry but still getting that exception.Here is the code that i have tried 我有一个Windows C#应用程序,当用户运行它时,我想将当前时间保存为某个注册表中的登录时间,以及当他关闭时作为注销时间。当我尝试时,它给了我请求的注册表访问权限,不允许例外。曾尝试授予该注册表权限,但仍收到该异常。这是我尝试过的代码

RegistrySecurity rs = new RegistrySecurity();
string currentUserStr = Environment.UserDomainName + "\\" + Environment.UserName;
rs.AddAccessRule(new RegistryAccessRule(currentUserStr, RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.FullControl, AccessControlType.Allow));                
RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SYSTEM", true).OpenSubKey("Test", true);
Rkey.SetAccessControl(rs);

I also tried using app.manifest to force application run as admin every time but i want to keep that as last option. 我也尝试使用app.manifest来强制每次以admin身份运行应用程序,但我想保留它作为最后的选择。 So is there any other solution to read/write registry ?? 那么还有其他解决方案来读取/写入注册表吗?

IMO, Your Application needs to run with elated privileges. IMO,您的应用程序需要以特权运行。 Try running Visual Studio as Administrator. 尝试以管理员身份运行Visual Studio。

I just run the code on my machine (windows 7 64 bits) as a Window Form . 我只是在我的计算机(Windows 7 64位)上以Window Form运行代码。 I did not have any problem with it (I could even remove the AddAccessRule line). 我对此没有任何问题(甚至可以删除AddAccessRule行)。

So the problem is not the code itself. 因此,问题不在于代码本身。 Did you try to change the value in the registry manually with the same user as you run your code ? 您是否尝试使用与运行代码相同的用户来手动更改registry的值? From which place (harddisk or network drive or internet..) do you run your code ? 您从哪个地方(硬盘,网络驱动器或Internet ..)运行代码? I know that running it from a network drive can give problems Let me know then maybe I can help you further 我知道从网络驱动器运行它会带来问题,请告诉我,也许我可以为您提供进一步的帮助

Access to HKLM (and that's what you're doing) requires administrative privileges 要访问HKLM(您正在执行的操作)需要具有管理权限

@Hitesh: you need to set MANIFESTUAC to "requireAdministrator" @Hitesh:您需要将MANIFESTUAC设置为“ requireAdministrator”

In Visual Studio, this is done in: Project properties -> Linker -> Manifest File and set: 在Visual Studio中,可通过以下方法完成:项目属性->链接器->清单文件,并设置:

  • Enable UAC to Yes, 启用UAC为是,
  • UAC Execution Level - requireAdministrator UAC执行级别-requireAdministrator
  • UAC Bypass UI - No UAC绕过用户界面-否

PS UAC is out there since Windows Vista... 自Windows Vista以来,PS UAC就已经存在...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM