Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Vivian River Avatar asked Dec 20 '11 17:12

Vivian River


3 Answers

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);
}
like image 114
ChrisWue Avatar answered Nov 19 '22 02:11

ChrisWue


It's better to serialize/unserialize your object as a string. In the following example, I use XML serialization. The "value" variable is the list object to store in the registry.

// using Microsoft.Win32;
// using System.IO;
// using System.Text;
// using System.Xml.Serialization;

string objectToSaveInRegistry;

using(var stream=new MemoryStream())
{
    new XmlSerializer(value.GetType()).Serialize(stream, value);
    objectToSaveInRegistry=Encoding.UTF8.GetString(stream.ToArray());
}

var registryKey=Registry.LocalMachine.OpenSubKey("MySpecialKey", true);
registryKey.SetValue("MySpecialValueName", objectToSaveInRegistry, RegistryValueKind.String);
like image 37
CedX Avatar answered Nov 19 '22 01:11

CedX


I would store the primitive values and then hydrate a poco when the data is pulled opposed to storing the poco itself.

like image 1
Jason Meckley Avatar answered Nov 19 '22 02:11

Jason Meckley