Save serializable object in registry in .net?

I am writing C # .net code that stores some values ​​in the registry. It worked fine 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); 

Error: "The type of the value object does not match the specified ValueKind register or the object cannot be correctly converted."

What can I do to save my object in the registry?

+6
source share
3 answers

You probably need to serialize your object first with a BinaryFormatter and store it in a byte array, which can then go 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); } 
+16
source

Better to serialize / unserialize your object as a string. In the following example, I am using XML serialization. The variable "value" is a list object for storage 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); 
+2
source

I would save the primitive values ​​and then humidify poco when the data is pushed against the storage of poco itself.

0
source

Source: https://habr.com/ru/post/904181/


All Articles