Search code examples
c#unit-testingregistrymsdtcregistrykey

RegistryKey Key.GetValue("keyName") is returning wrong values in Unit Test c# project


I have this code:

RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSDTC\\Security");
if (key != null)
{
      Object o = key.GetValue("NetworkDtcAccessInbound");
      if (o != null)
      {
      }
}

It returns the correct value (1) when i use in normal project, but in Unit Test project it returns wrong value (0), i know coz i see in regedit.

If i check for these keys: LuTransactions, XaTransactions, it returns correct, even in Unit Test Project.

If i check for these: NetworkDtcAccessInbound, NetworkDtcAccessOutbound, NetworkDtcAccess it returns wrong just in Unit Test Project

anyone knows about this behavior?


Solution

  • As @AlexeiLevenkov said it was a x86/x64 mismatch, the Unit Test runs as x86, but my system is x64, i did a web search for a code that read registry for each operation system type.

    The code below is for x86 operation system, but my computer is x64, so the code below returned a wrong value (value = 0).

    string value32 = string.Empty;
    RegistryKey localKey32 = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
    localKey32 = localKey32.OpenSubKey("Software\\Microsoft\\MSDTC\\Security");
    if (localKey32 != null)
    {
        value32 = localKey32.GetValue("NetworkDtcAccessInbound").ToString();
    }
    

    The code below is for x64 operation system, my computer is x64, so the code below returned a correct value (value = 1).

    string value64 = string.Empty;
    RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
    localKey = localKey.OpenSubKey("Software\\Microsoft\\MSDTC\\Security");
    if (localKey != null)
    {
        value64 = localKey.GetValue("NetworkDtcAccessInbound").ToString();
    }
    

    thats all folks.