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
            }

        }
    }
}
相关推荐
公子小六9 小时前
基于.NET的Windows窗体编程之WinForms滑块与上下控件
windows·microsoft·c#·.net·winforms
曹牧10 小时前
C#:文本文件读取
服务器·前端·c#
oliver_sys_log10 小时前
老项目 json-lib 2.4 JSONTokener 精度丢失问题排查
json
2601_9673387110 小时前
C#上位机开发零基础入门到精通全套视频
开发语言·c#
IT_Octopus13 小时前
JSON 日志里的 `{“$ref“:“$.xxx“}`:从 fastjson 兼容包到原生 fastjson2 的迁移实录
开发语言·python·json
czhc114007566315 小时前
2026-09-03 博客:配置与密码 · 合并代码 · 超时排查
c#
格林威17 小时前
C#图像夜间识别率提升:使用OpenCvSharp和Halcon融合DeepSORT实现复杂场景下准确识别
开发语言·人工智能·数码相机·机器学习·计算机视觉·c#·视觉检测
数据狐(Datafox)18 小时前
mercadolibre.item_get 工程实战:美客多商品详情API技术解析与落地应用
java·人工智能·mysql·json
Fcy64819 小时前
Linux下 应⽤层⾃定义协议与序列化(JSON方法)
linux·json
曹牧19 小时前
C#:线程间操作无效,不是从创建控件线程访问
开发语言·c#