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
            }

        }
    }
}
相关推荐
曹牧7 小时前
C#:输入的字符串格式不正确
c#
Dxy123931021611 小时前
MySQL JSON 生成列索引原理、实战与坑点
mysql·adb·json
根号五12 小时前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰13 小时前
C#:接收从打开方式打开的参数
c#
宝桥南山14 小时前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
开开心心_Every14 小时前
文件查重软件批量删除重复文件释放空间
java·开发语言·c#·计算机外设·ocr·excel·perl
l1t14 小时前
DeepSeek总结的DuckDB 从 JSON 字符串到类型化列
数据库·sql·json
波力海苔夹心脆67515 小时前
VisionPro 与 VisionMaster 对比(上):软件定位、开发环境与核心视觉工具对照
图像处理·算法·计算机视觉·c#·视觉检测·个人开发·vp9
疯狂戴夫冒险16 小时前
歇一会 · 久坐休息提醒工具(番茄钟)工具分享
c#
积流成海16 小时前
CSV与JSON转换:RFC 4180 转义规则与 Excel 中文乱码
json·excel·盘子工具站