0

I have a piece of code working that serialized a string into XML with XmlSerializer. I want to serialize the same string into binary and Not xml, I have tried different codes but none working, if possible please rewrite the following code to output me a serialized binary and store it in a variable.

public  class SerialTest
{
    public static void Main(string[] s)
    {
        String test = "ASD";
        string serializedData = string.Empty;                   

        XmlSerializer serializer = new XmlSerializer(test.GetType());
        using (StringWriter sw = new StringWriter())
        {
            serializer.Serialize(sw, test);
            serializedData = sw.ToString();
            Console.WriteLine(serializedData);
            Console.ReadLine();
        }
    }
}

What I actually want is to have a code that serialize an object and give me the serialized binary as output in a variable and not XML.

Emily Wong
  • 307
  • 2
  • 10

1 Answers1

1

If you need to store Binary Serialization output inside a string, for that you can use ToBase64String like following.

String test = "ASD";
string serializedData = string.Empty;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, test);
memoryStream.Flush();
memoryStream.Position = 0;
serializedData = Convert.ToBase64String(memoryStream.ToArray());
PSK
  • 16,571
  • 4
  • 31
  • 42
  • Thanks, how can i have output as Hex and not base64string? – Emily Wong Feb 10 '19 at 07:21
  • You can try Encoding.Default.GetString(memoryStream.ToArray()) – PSK Feb 10 '19 at 07:23
  • For more details to output a byte array, you can check this https://stackoverflow.com/questions/10940883/c-converting-byte-array-to-string-and-printing-out-to-console – PSK Feb 10 '19 at 07:25