Home > database >  Mongodb.Bson BsonBinaryWriter can't write field with name
Mongodb.Bson BsonBinaryWriter can't write field with name

Time:01-13

I'm trying to write int value to BsonBinaryWriter using WriteInt32, but receive exception "WriteName can only be called when State is Name, not when State is Initial".

code sample

using MongoDB.Bson;
using MongoDB.Bson.IO;
        
BsonBinaryWriter writer = new BsonBinaryWriter(new MemoryStream());
writer.WriteInt32("t", 1); // receive exception here 

CodePudding user response:

you should call WriteStartDocument first since what you're doing is creating a BSON document. So you're trying to add t : 1 value, but given that BSON document should roughly speaking correspond to JSON rules, you should open a bracket { (via WriteStartDocument) and close it at the end of a document (via WriteEndDocument).

See:

        using var memoryStream = new MemoryStream();
        using var writer = new BsonBinaryWriter(memoryStream);
        writer.WriteStartDocument();
        writer.WriteInt32("t", 1); // receive exception here
        writer.WriteEndDocument();

        memoryStream.Position = 0;

        using var reader = new BsonBinaryReader(memoryStream);
        var context = BsonDeserializationContext.CreateRoot(reader);
        var document = BsonDocumentSerializer.Instance.Deserialize(context);
        Console.WriteLine(document.ToString()); // => { "t" : 1 }
  • Related