简体   繁体   English

C#二进制序列化为变量

[英]C# Binary serialization into a variable

I have a piece of code working that serialized a string into XML with XmlSerializer. 我有一段代码使用XmlSerializer将字符串序列化为XML。 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. 我想将相同的字符串序列化为二进制而不是xml,但我尝试了不同的代码,但均无法正常工作,如果可能,请重写以下代码以向我输出序列化的二进制并将其存储在变量中。

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. 我真正想要的是拥有一个序列化对象的代码,并将序列化的二进制文件作为变量而不是XML输出给我。

If you need to store Binary Serialization output inside a string , for that you can use ToBase64String like following. 如果需要将Binary Serialization输出存储在string ,可以使用ToBase64String ,如下所示。

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM