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 小时前
使用 MWGA 帮助 7 万行 Winforms 程序快速迁移到 WEB 前端
前端·c#·.net
老骥伏枥~11 小时前
【C# 入门】程序结构与 Main 方法
开发语言·c#
全栈师12 小时前
java和C#的基本语法区别
java·开发语言·c#
钰fly12 小时前
联合编程(加载单个工具,ini读写,图片读写,setting存储)
c#
天若有情67313 小时前
XiangJsonCraft v1.2.0重大更新解读:本地配置优先+全量容错,JSON解耦开发体验再升级
前端·javascript·npm·json·xiangjsoncraft
FuckPatience14 小时前
C# 对象初始化器对属性赋值vs构造函数里对属性赋值
c#
m0_7482331715 小时前
C语言vsC#:核心差异全解析
c语言·开发语言·c#
MyBFuture16 小时前
C# 关于联合编程基础
开发语言·c#·visual studio·vision pro
Sylvia33.16 小时前
足球“文字直播/事件流”API详解:解码比赛的数字DNA
java·服务器·前端·json
Sunsets_Red16 小时前
单调队列优化dp
c语言·c++·算法·c#·信息学竞赛