Search code examples
c#.netserializationregistry

Save serializable object to registry in .net?


I'm writing some C# .net code that saves some values to the registry. It worked fine up until I wanted to save some binary data.

I have a List<MyType> object where MyType looks like this:

[Serializable] public class MyType
{
 public string s {get;set;}
 public string t {get;set;}
}

I get an error with the following code:

List<MyType> objectToSaveInRegistry = getList();
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(MySpecialKey, true);
registryKey.SetValue("MySpecialValueName", objectToSaveInRegistry , RegistryValueKind.Binary);

The error is: "The type of the value object did not match the specified Registry ValueKind or the object could not be properly converted."

What can I do so that I can save my object in the registry?


Solution

  • You probably need to serialize your object first with the help of the BinaryFormatter and store it in a byte array which you then can pass to SetValue. I doubt that SetValue will serialize the object for you.

    Quick example:

    using (var ms = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(ms, objectToSaveInRegistry);
        var data = ms.ToArray();
        registryKey.SetValue("MySpecialValueName", data, RegistryValueKind.Binary);
    }