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
  • 297
  • 3
  • 10
  • Have you looked into this https://learn.microsoft.com/en-us/dotnet/standard/serialization/basic-serialization ? – Gabriel Costin Feb 10 '19 at 07:17
  • @GabrielCostin, Yes but it store the result in a file, I cant have it in a variable. – Emily Wong Feb 10 '19 at 07:18
  • Can you be clearer about your requirements? Do you want real binary data (`byte[]`) or Hex (`string`) ? And maybe also indicate what you need it for. – H H Feb 10 '19 at 09:40

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
  • 17,547
  • 5
  • 32
  • 43
  • 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