I am trying to create a subkey but am getting an IO exception. The subkey remains null and the error occurs on the line that attempts to create it. Here is what the IO Exception says:
The nesting level exceeds 510. -or- A system error occurred, such as deletion of the key, or an attempt to create a key in the LocalMachine root.
RegistryKey sk1 = Registry.LocalMachine.OpenSubKey(KEY_NAME.ToUpper(), true);
// If the RegistrySubKey doesn't exist (i.e. null)
if (sk1 == null)
{
try
{
// this line causes the error
sk1 = Registry.LocalMachine.CreateSubKey(KEY_NAME.ToUpper());
// Save the the current date
sk1.SetValue(KEY_NAME.ToUpper(), keyVal);
}
catch (Exception e)
{
//on error, return false
return false;
}
}
It can be one of either things:
You don't have permission to write to the LocalMachine registry. You can try replacing the Registry.LocalMachine.CreateSubKey to Registry.CurrentUser.CreateSubKey
With this line -
RegistryKey sk1 = Registry.LocalMachine.OpenSubKey(KEY_NAME.ToUpper(), true);
You are opening the SubKey with 'write' permissions. You should use CreateSubKey instead. It creates new SubKey or opens an existing one for changes. Could be after you open it with 'OpenSubKey' and trying again with 'CreateSubKey' causes this error. (either way, you don't need to use OpenSubKey)