4
votes

Why doesn't this work? I am trying to create a registry key under [HKEY_LOCAL_MACHINE\SOFTWARE\MyService], but nothing is created.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace RegistryKey
{
    class Program
    {
        static void Main(string[] args)
        {
            const string SUB_KEY_NAME = @"SOFTWARE\MyService";

            // Create a subkey named MyService under HKEY_LOCAL_MACHINE.
            Registry.LocalMachine.CreateSubKey(SUB_KEY_NAME);
        }
    }
}

Update: Never mind. I'm an idiot. I used the Remote registry Editor to inspect the registry in the belief that it would show the same as regedit. It didn't! I can see the path using regedit.

2
I assume you aren't getting an exception when that code executes? - Cody Gray♦
That is correct. No exception. - Kasper Hansen

2 Answers

7
votes

You don't have write access to HKLM. If you want to write here then you need to either:

  • run the process as an elevated user, or.
  • only attempt to write to HKLM during install.
1
votes

Try with this code:

RegistryKey regkey = Registry.CurrentUser;
regkey = regkey.CreateSubKey(SUB_KEY_NAME); //this is the path then you create yours keys
regkey.SetValue("Install", "ok"); //name of key exp:(install) and then the value exp:(ok)