Serialize() public method

Serializes an object to a BsonWriter.
public Serialize ( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) : void
bsonWriter BsonWriter The BsonWriter.
nominalType System.Type The nominal type.
value object The object.
options IBsonSerializationOptions The serialization options.
return void
Exemplo n.º 1
0
        internal void Save(string saveAs, FileFormat format)
        {
            if (string.IsNullOrEmpty(saveAs))
            {
                saveAs = FilePath;
                format = FileFormat;
            }

            if (saveAs == null)
                throw new InvalidOperationException("File path should be provided either on opening or saving.");

            if (format == FileFormat.Auto)
                format = saveAs.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? FileFormat.Json : FileFormat.Bson;

            var tmp = File.Exists(saveAs) ? saveAs + ".tmp" : saveAs;

            var serializer = new BsonDocumentSerializer();
            var options = DocumentSerializationOptions.Defaults;

            if (format == FileFormat.Json)
            {
                using (var streamWriter = new StreamWriter(tmp))
                {
                    foreach (var document in Documents)
                    {
                        using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
                        using (var bsonWriter = BsonWriter.Create(stringWriter, Actor.DefaultJsonWriterSettings))
                        {
                            serializer.Serialize(bsonWriter, typeof(BsonDocument), document, options);
                            streamWriter.WriteLine(stringWriter.ToString());
                        }
                    }
                }
            }
            else
            {
                using (var fileStream = File.Open(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
                using (var bsonWriter = BsonWriter.Create(fileStream))
                {
                    foreach (var document in Documents)
                        serializer.Serialize(bsonWriter, typeof(BsonDocument), document, options);
                }
            }

            if (!object.ReferenceEquals(tmp, saveAs))
                File.Replace(tmp, saveAs, null);
        }