title: C# UnauthorizedAccessException on RegistryKey CreateSubKey
body: <p>I get an <a href="http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception%28v=VS.80%29.aspx" rel="nofollow noreferrer">UnauthorizedAccessException</a> any time I try to call <a href="http://msdn.microsoft.com/en-us/library/ad51f2dx%28v=VS.80%29.aspx" rel="nofollow noreferrer">CreateSubKey</a> in my code.</p>
  
  <pre><code>const string regKeyPath = @"Software\Apps\jp2code.net\FTMaint";
  
  private void BuildRegistry() {
    string[] split = regKeyPath.Split('\\');
    keyMaker(Registry.LocalMachine, split, 0);
  }
  
  private static void keyMaker(RegistryKey key, string[] path, int index) {
    string keyValue = path[index++];
    RegistryKey key2;
    if (!String.IsNullOrEmpty(keyValue)) {
      string subKey = null;
      string[] subKeyNames = key.GetSubKeyNames();
      foreach (var item in subKeyNames) {
        if (keyValue == item) {
          subKey = item;
        }
      }
      if (String.IsNullOrEmpty(subKey)) {
        key2 = key.CreateSubKey(keyValue);
      } else {
        key2 = key.OpenSubKey(subKey);
      }
      //key2 = key.OpenSubKey(keyValue, String.IsNullOrEmpty(subKey));
    } else {
      key2 = key;
    }
    if (index &lt; path.Length) {
      try {
        keyMaker(key2, path, index + 1);
      } finally {
        key2.Close();
      }
    }
  }
  </code></pre>
  
  <p>I found a post where someone was having a similar problem <a href="http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/e70646e6-35b2-4397-b564-ff7cf31fa7b4" rel="nofollow noreferrer">>> HERE &lt;&lt;</a> on MSDN Social, but the solution there (to use the overloaded OpenSubKey method) only returned a NULL <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey%28v=VS.80%29.aspx" rel="nofollow noreferrer">RegistryKey</a> for me.</p>
  
  <p>This is for a Windows Mobile 5 device emulator.</p>
  
  <p><strong>Can anyone see what I'm doing wrong?</strong></p>
  
  <p>The error is thrown the first time the code reaches a key that does not exist and tries to create it.</p>
  
  <p>Thanks!</p>
  
  <p><img src="https://i.stack.imgur.com/rmh51.png" alt="screen shot"></p>