I'm trying to set a registry key in my C# code, but it doesn't work all the time. Sometimes it does work, sometimes it doesn't. I'm starting to get crazy... In previous projects I had no problems writing and reading to the registry, but I do now.
Here's the code I'm using:
string newVersion = "10A";
RegistryKey key = null;
try
{
key = Registry.CurrentUser.CreateSubKey("Software\\stuff1\\stuff2 " + newVersion + "\\" + newVersion + "\\stuff3\\Settings", RegistryKeyPermissionCheck.ReadWriteSubTree);
key.SetValue("CopyConvertDone", "1", RegistryValueKind.String);
key.Flush();
rep.Message("CopyConvertDone registry key set for revision: " + newVersion);
}
catch (Exception e)
{
rep.Error(e);
}
finally
{
if (key != null)
{
key.Close();
}
else
{
rep.Error("Registry key is set to null.");
}
}
What I already tried but didn't work: - Instead of using CreateSubKey I tried OpenSubKey with the write-parameter set to true. - Added the .Flush() method. - Did a Thread.Pause(2000) to give it some time before progressing my program (which needs this registry key)
I don't get any error and the subkey already exists, but the value (CopyConvertDone) doesn't.
Can anyone see a problem in this code and has a possible solution?