Search code examples
c#.netserializationbinaryformatter

make string properties unreadable after object serialization


I'm using this code to serialize my objects

public static void SerializeObject(string filename, MyObject objectToSerialize)
{
    Stream stream = File.Open(filename, FileMode.Create);
    BinaryFormatter bformatter = new BinaryFormatter();

    bformatter.Serialize(stream, objectToSerialize);
    stream.Close();            
}

Serialization and deserialization works fine, but I'm wondering how can I using serialization make objects string properties make unreadable. Now after serialization when user opens file in text editor string properties are readible between other ugly characters.


Solution

  • This is happening because you are using a BINARY formatter, which stores the data in binary form.

    So, for example, when storing a string it may prefix the raw string with the length of the string as a binary 32-bit number - which would result in 4 bytes which do not represent characters (and will show "ugly characters" in a text editor).

    If you want a human-readable serialized version, you should use XML serialization.

    Here's a sample console app that demonstrates how to binary serialize, and two ways to XML serialize the same class:

    using System;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace Demo
    {
        [Serializable]
        public class Test
        {
            public string Text;
            public int    Number;
        }
    
        internal class Program
        {
            private static void Main()
            {
                var test = new Test {Text = "Some text", Number = 12345 };
    
                // Creates a binary file:
    
                using (var stream = File.Create(@"c:\\test\\test.bin"))
                {
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(stream, test);
                }
    
                // Creates an XML file using XmlSerializer:
    
                using (var stream = File.Create(@"c:\\test\\test1.xml"))
                {
                    var formatter = new XmlSerializer(typeof(Test), defaultNamespace : "");
                    formatter.Serialize(stream, test);
                }
    
                // Creates an XML file using XmlWriter and DataContractSerializer:
    
                DataContractSerializer serializer = new DataContractSerializer(test.GetType());
    
                using (var streamWriter = File.CreateText(@"c:\\test\\test2.xml"))
                using (var xmlWriter    = XmlWriter.Create(streamWriter, new XmlWriterSettings { Indent = true }))
                {
                    serializer.WriteObject(xmlWriter, test);
                }
            }
        }
    }