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.

3
  • Have you looked into this learn.microsoft.com/en-us/dotnet/standard/serialization/… ? Commented Feb 10, 2019 at 7:17
  • @GabrielCostin, Yes but it store the result in a file, I cant have it in a variable. Commented Feb 10, 2019 at 7: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. Commented Feb 10, 2019 at 9:40

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, how can i have output as Hex and not base64string?
You can try Encoding.Default.GetString(memoryStream.ToArray())
For more details to output a byte array, you can check this stackoverflow.com/questions/10940883/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.