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
            }

        }
    }
}
相关推荐
宝桥南山15 小时前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore
hixiong12318 小时前
C# OpenvinoSharp部署INSID3
开发语言·人工智能·ai·c#·openvinosharp
星辰徐哥19 小时前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung19 小时前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker70719 小时前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio
SKY -dada19 小时前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
William_cl1 天前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net
武藤一雄1 天前
WPF:MessageBox系统消息框
前端·microsoft·c#·.net·wpf
武藤一雄1 天前
WPF进阶:万字详解WPF如何性能优化
windows·性能优化·c#·.net·wpf·.netcore·鲁棒性
ID_180079054731 天前
Python 实现亚马逊商品详情 API 数据准确性校验(极简可用 + JSON 参考)
java·python·json