C#读写Bson格式的文件

介绍

在VS2022控制台项目中,通过NuGet安装Newtonsoft.Json.Bson1.0.3:

该库用来读写bson格式的文件,也就是json文件的二进制版本的文件。

示例

简单封装的BsonUtil工具类

csharp 复制代码
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;

namespace Util
{
    public class BsonUtil
    {    
        public static bool Read<T>(string bsonPath, out T t)
        {
            t = default;
            if (!File.Exists(bsonPath))
            {
                return false;
            }
            try
            {
                var bytes = File.ReadAllBytes(bsonPath);
                MemoryStream ms = new MemoryStream(bytes);
                using (BsonReader reader = new BsonReader(ms))
                {
                    JsonSerializer serializer = new JsonSerializer();

                    try
                    {
                        t = serializer.Deserialize<T>(reader);
                        return true;
                    }
                    catch (Exception e)
                    {
                        t = default;
                        return false;
                    }
                }
            }
            catch (System.Exception e)
            {
                t = default;
                return false;
            }

        }

     
        public static void Save(string fileFullPath, object obj)
        {
            MemoryStream ms = new MemoryStream();
            using (BsonWriter writer = new BsonWriter(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, obj);
            }

            File.WriteAllBytes(fileFullPath, ms.ToArray());
        }
    }
}

调用示例

先是将一个实体类存储为bson文件,再将其读取进来,可以打断点查看读进来的属性。

csharp 复制代码
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace Demos{
    public class BsonDemos
    {
        public class Building
        {
            public List<Layer> layers = new List<Layer>();
        }
        public class Layer
        {
            public string name;
            public bool visible;
            public List<Entity> entities = new List<Entity>();
        }
        public class Entity
        {
            public int id;
            public string type;
        }
        public static void Test()
        {
            var bui = new Building();
            var layer = new Layer() { name = "0" };
            layer.entities.Add(new Entity { id = 1, type = "LINE" });
            layer.entities.Add(new Entity { id = 2, type = "CIRCLE" });
            layer.entities.Add(new Entity { id = 3, type = "ARC" });
            bui.layers.Add(layer);
            layer = new Layer() { name = "1" };
            layer.entities.Add(new Entity { id = 4, type = "POLYLINE" });
            layer.entities.Add(new Entity { id = 5, type = "INSERT" });
            layer.entities.Add(new Entity { id = 6, type = "POINT" });
            bui.layers.Add(layer);

            var path = "./bui.d";
            BsonUtil.Save(path, bui);
            if (BsonUtil.Read(path, out Building bui2))
            {
						  //成功创建
            }
            if (BsonUtil.Read(path, out JContainer j))
            {
                var layers = j["layers"];
                var layer1 = layers[0];
                var layer1Name = layer1["name"].ToString();
                //to do
            }

        }
    }
}
相关推荐
爱说实话10 小时前
C# 20260109
开发语言·c#
电商API&Tina11 小时前
电商数据采集 API:驱动选品、定价、运营的数据分析核心引擎
大数据·开发语言·人工智能·python·数据分析·json
一心赚狗粮的宇叔20 小时前
中级软件开发工程师2025年度总结
java·大数据·oracle·c#
cplmlm21 小时前
EF Core使用CodeFirst生成postgresql数据库表名以及字段名用蛇形命名法,而类名仍使用驼峰命名
c#
lingxiao168881 天前
WebApi详解+Unity注入--下篇:Unity注入
unity·c#·wpf
lingxiao168881 天前
WebApi详解+Unity注入--中篇:.net core的WebAPI
unity·c#·.netcore
ServBay1 天前
C# 成为 2025 年的编程语言,7个C#技巧助力开发效率
后端·c#·.net
ID_180079054731 天前
闲鱼商品详情API接口基础架构解析
json