public static void CopyToBson(string inputPath, string outputPath, FileMode fileMode = FileMode.CreateNew)
 {
     using (var textReader = File.OpenText(inputPath))
         using (var jsonReader = new JsonTextReader(textReader))
             using (var oFileStream = new FileStream(outputPath, fileMode))
                 using (var dataWriter = new BsonDataWriter(oFileStream))
                 {
                     dataWriter.WriteToken(jsonReader);
                 }
 }
Ejemplo n.º 2
0
    public static void CopyToBson(JsonReader jsonReader, Stream stream)
    {
        var rootTokenType = jsonReader.ReadToContentAndAssert().TokenType;

        if (!stream.CanSeek || rootTokenType != JsonToken.StartArray)
        {
            using (var dataWriter = new BsonDataWriter(stream)
            {
                CloseOutput = false
            })
            {
                dataWriter.WriteToken(jsonReader, stream.CanSeek);
            }
        }
        else
        {
            stream.Flush();                     // Just in case.
            var initialPosition = stream.Position;
            var buffer          = new byte[256];
            WriteInt(stream, 0, buffer);                     // CALCULATED SIZE TO BE CALCULATED LATER.
            ulong index = 0;
            while (jsonReader.ReadToContentAndAssert().TokenType != JsonToken.EndArray)
            {
                var bsonType = GetBsonType(jsonReader.TokenType, jsonReader.ValueType);
                stream.WriteByte(unchecked ((byte)bsonType));
                WriteString(stream, index.ToString(NumberFormatInfo.InvariantInfo), buffer);
                using (var dataWriter = new BsonDataWriter(stream)
                {
                    CloseOutput = false
                })
                {
                    dataWriter.WriteToken(jsonReader);
                }
                index++;
            }

            stream.WriteByte((byte)0);
            stream.Flush();
            var finalPosition = stream.Position;
            stream.Position = initialPosition;
            var size = checked ((int)(finalPosition - initialPosition));
            WriteInt(stream, size, buffer);                     // CALCULATED SIZE TO BE CALCULATED LATER.

            stream.Position = finalPosition;
        }
    }