How to binary serialize an object such as Font and store it in Windows Registry then deserialize it in C#

Smart Notepad App (At least smarter than some unnamed notepads)Say you want to make a notepad like application, and you want to let the user choose the default font for the text and that should be remembered each time the user open the app. The solution is instead of saving each font property, you save the whole class object. But you need to serialize the class using Binary in order to be able to store it in Windows Registry.

Below is the class that create registry keys, and can save and serialize a font object, and deserialize it back again using IFormatter.Serialize, IFormatter.Deserialize and MemoryStream.


For C# (C-Sharp)

The registry class

using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; using System.Drawing; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; class winreg { private RegistryKey prgReg; private RegistryKey recentReg; public winreg() { RegistryKey reg = Registry.CurrentUser.OpenSubKey(“software”, true); RegistryKey regMilky = reg.CreateSubKey(“MyBrand”); prgReg = regMilky.CreateSubKey(“MySoftware”); } public void save_font(Font fnt) { RegistryKey fntReg = prgReg.CreateSubKey(“Font”); IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); formatter.Serialize(stream,fnt); stream.Flush(); byte[] buffer = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, (int)stream.Length); stream.Close(); fntReg.SetValue(“FontInfo”, buffer,RegistryValueKind.Binary); } public bool get_font(ref Font fnt) { RegistryKey fntReg = prgReg.CreateSubKey(“Font”); if (fntReg.GetValue(“FontInfo”) != null) { byte[] buffer = (byte[])fntReg.GetValue(“FontInfo”); IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(buffer); fnt = (Font)formatter.Deserialize(stream); stream.Close(); return true; }else return false; } }

Below is how to use the above class.

winreg WinRegClass = new winreg(); Font fnt = MyTextBox.Font; if (WinRegClass.get_font(ref fnt)!=false) { MyTextBox.Font = fnt; }

This is not a fine work. I’m still practicing C#, so, don’t judge (; Yesterday I wanted to play a DOS game using DosBox, but somehow ended up practicing more C#. You see: Games=useful.