Search code examples
c#registry

Read Registry Value, cast as String


I'm trying to read a REG_SZ value from the registry, then convert it to a string for later use.

I read it from the registry using

RegistryKey key
ArrayList m = new ArrayList();
if(Environment.is64BitOperatingSystem)
   key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
else
   key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);

if(key != null)
{
  object o = key.openSubKey(SOFTWARE\\xx\\yy\\zz).GetValue("Version")
  if (o != null)
    m.add(o.toString())
} 

However, when I do this, an exception is thrown, saying

Application:abc.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidCastException

Is there a problem with the way I'm trying to cast this registry value? I need it as a string to manipulate and compare.


Solution

  • Fixed! Looks like it wasn't the cast to string that was the problem. I was trying to add the

    o.toString()
    

    to an ArrayList and adding the string to the ArrayList was causing the cast problem.

    Thanks!