I get an UnauthorizedAccessException any time I try to call CreateSubKey in my 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 < path.Length) {
try {
keyMaker(key2, path, index + 1);
} finally {
key2.Close();
}
}
}
I found a post where someone was having a similar problem >> HERE << on MSDN Social, but the solution there (to use the overloaded OpenSubKey method) only returned a NULL RegistryKey for me.
This is for a Windows Mobile 5 device emulator.
Can anyone see what I'm doing wrong?
The error is thrown the first time the code reaches a key that does not exist and tries to create it.
Thanks!
All three of these work fine for me on the WinMo 6 Emulator.
Create a root key:
using (var swKey = Registry.LocalMachine.CreateSubKey("foo"))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}
Create a subkey via path
using (var swKey = Registry.LocalMachine.CreateSubKey("software\\foo"))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}
Create a subkey directly:
using (var swKey = Registry.LocalMachine.OpenSubKey("software", true))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}