如何使用字符串而不是流?

时间:2016-08-10 18:36:33

标签: c# stream

我需要使用它:

http://www.newtonsoft.com/json/help/html/SerializeToBson.htm

这是将对象转换为BSON格式的代码。我感兴趣的代码是:

System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (Newtonsoft.Json.Bson.BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
{
    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
    serializer.Serialize(writer, message);
}

但是,我想把结果放在一个字符串中。那么我是否真的必须使用流或文件来编写内容,然后读取它以将其放入字符串中?

必须有更好的方法来做到这一点吗?

1 个答案:

答案 0 :(得分:4)

您可以使用StreamReader.ReadToEnd()获取字符串

        string bsonText = "";

        using(MemoryStream stream = new MemoryStream())
        using(StreamReader reader = new StreamReader(stream))
        using (BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(writer, message);

            stream.Position = 0;
            bsonText = reader.ReadToEnd();
        }

或者Encoding.UTF8.GetString()

        using(MemoryStream stream = new MemoryStream())
        using (BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(writer, message);

            bsonText = Encoding.UTF8.GetString(stream.ToArray());
        }
BTW谁知道你将从中获得什么,因为 BSON 是一个二进制对象表示,它不像JSON!