在 C# 中将密钥写入 Windows 注册表

Write keys into the Windows registry in C#

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

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

我们已经能够通过 P/Invoking LoadUserProfile.

获取用户 SID,并将其添加到注册表中

但是,当尝试写入环境子键时出现问题:

        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)

宾果!

来自 RegistryKey.OpenSubKey(String) 上的 MSDN article

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.