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?
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);
}
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);
I would store the primitive values and then hydrate a poco when the data is pulled opposed to storing the poco itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With