gpt4 book ai didi

c# - 在 C# 中将 key 写入 Windows 注册表

转载 作者:可可西里 更新时间:2023-11-01 10:03:32 25 4
gpt4 key购买 nike

我们正在尝试使用 C# 将键值对添加到 Windows 注册表中。

要写的关键是另一个用户的环境变量。用户将成为服务用户,永远不会登录。

我们已经能够通过 P/Invoking LoadUserProfile 获取用户 SID,并将其添加到注册表。

但是,当尝试写入 Environment Sub Key 时出现问题:

        using (var key = Registry.Users.OpenSubKey(userSid + "\\Environment"))
{
if (key == null)
{
Debug.WriteLine("Key was null (typical)");
return;
}

key.SetValue("A", "B");
}

这会抛出一个 UnauthorizedAccessException 以及真正有用的消息

Cannot write to the registry key

应用程序以管理员身份运行。

出于显而易见的原因,我猜测这与安全访问控制有关。我可以获得访问控制,使用 var security = key.GetAccessControl(); 但是,我不知道要更改哪些值才能写入环境。

只是为了记录,我可以将值写入一些其他键,例如 HKEY_USERS 本身,或 HKEY_LOCAL_MACHINE 本身,但我不能写入 HKEY_LOCAL_MACHINE\Public 例如。

如果有帮助,这里是堆栈跟踪:

************** Exception Text **************
System.UnauthorizedAccessException: Cannot write to the registry key.
at System.ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.EnsureWriteable()
at Microsoft.Win32.RegistryKey.SetValue(String name, Object value, RegistryValueKind valueKind)
at Microsoft.Win32.RegistryKey.SetValue(String name, Object value)
at TestingEnvVariables.Form1.GetVariablesButtonClick(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

最佳答案

宾果!

来自MSDN articleRegistryKey.OpenSubKey(String) 上:

Retrieves a subkey as read-only.

您需要 RegistryKey.OpenSubKey(String,‖Boolean) ( MSDN article ):

Retrieves a specified subkey, and specifies whether write access is to be applied to the key.

关于c# - 在 C# 中将 key 写入 Windows 注册表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42852159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com