dave
dave

Reputation:

NullReferenceException when setting a Registry Value

I am getting a NullReference Exception when I try to set a value to a registry key. Below is my code. Does anyone know why?

using System;
using Microsoft.Win32;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
           RegistryKey myKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\Current Version\\Policies\\System", true);
            myKey.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);

        }
    }
}

Upvotes: 1

Views: 552

Answers (3)

dave
dave

Reputation:

The problem was the space between Current Version.

Upvotes: 0

Ray
Ray

Reputation: 46585

Current Version should be one word. I.e. CurrentVersion.

Edit: I also agree with Jared you should be using CreateSubKey as well.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754655

Try CreateSubKey instead of OpenSubKey. The latter will return null if the key does not exist. It's likely the key does not exist and that is why you hit a null reference on the next line.

Upvotes: 4

Related Questions