tags:

views:

128

answers:

3

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?

+3  A: 

The code looks alright to me, however if it's working some of the time then perhaps use Process Monitor to see what calls are being made to the registry and what is succeeding/failing.

Antony Koch
A: 

Looks correct. Maybe try to remove Flush. From MSDN: An application should only call Flush if it must be absolute certain that registry changes are recorded to disk. In general, Flush rarely, if ever, need be used.

Your already closing the RegistryKey in the finally statement.

PoweRoy
A: 

Had something similar happen to me just now, and using Process Monitor as suggested by Antony I discovered Windows 7 was redirecting my writes to a key under HKCU\Software\Classes\VirtualStore\MACHINE.

Just a pointer in case anybody else has this issue.

Matt