You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#控制台应用配置文件中设置特定变量类型并持久化byte数组列表

在C#控制台应用中持久化存储byte数组列表的几种方法

下面给你两种可行的方案,都能实现重启应用后保留原有数据的需求:

方案一:用JSON文件存储(简单易上手)

这种方式不用折腾配置文件的复杂节点,直接序列化列表到JSON文件,读写逻辑简洁直观。

实现步骤:

  • 如果是.NET Core/5+版本,直接用自带的System.Text.Json;如果是.NET Framework,通过NuGet安装Newtonsoft.Json(Json.NET)即可
  • 编写一个工具类处理读写操作:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json; // .NET Core/5+使用此命名空间
// using Newtonsoft.Json; // .NET Framework使用此命名空间

public static class ByteListStorage
{
    // 存储文件路径:和应用程序同目录下的byteLists.json
    private static readonly string _filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "byteLists.json");

    // 保存byte数组列表到文件
    public static void SaveByteLists(List<byte[]> byteLists)
    {
        var options = new JsonSerializerOptions { WriteIndented = true }; // 格式化JSON,方便人工查看
        string json = JsonSerializer.Serialize(byteLists, options);
        // 用Json.NET的话替换为:string json = JsonConvert.SerializeObject(byteLists, Formatting.Indented);
        File.WriteAllText(_filePath, json);
    }

    // 从文件加载byte数组列表
    public static List<byte[]> LoadByteLists()
    {
        if (!File.Exists(_filePath))
            return new List<byte[]>();

        string json = File.ReadAllText(_filePath);
        return JsonSerializer.Deserialize<List<byte[]>>(json) ?? new List<byte[]>();
        // 用Json.NET的话替换为:return JsonConvert.DeserializeObject<List<byte[]>>(json) ?? new List<byte[]>();
    }
}

使用示例:

// 加载已保存的列表
var myByteLists = ByteListStorage.LoadByteLists();

// 添加新的byte数组
myByteLists.Add(new byte[] { 0x01, 0x02, 0x03 });

// 保存更新后的列表
ByteListStorage.SaveByteLists(myByteLists);

重启应用后,调用LoadByteLists()就能获取之前保存的数据。

方案二:用App.config自定义配置节(传统配置文件方式)

如果一定要依托应用的配置文件(App.config)实现,可以通过自定义配置节来存储byte数组列表。

实现步骤:

  1. 在App.config中添加自定义配置节及数组配置项:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!-- 注册自定义配置节,注意替换命名空间和程序集名称 -->
    <section name="byteListSettings" type="YourNamespace.ByteListSection, YourAssemblyName" />
  </configSections>

  <byteListSettings>
    <byteLists>
      <!-- 用十六进制字符串存储byte数组,无分隔符 -->
      <add value="010203" />
      <add value="040506" />
    </byteLists>
  </byteListSettings>
</configuration>
  1. 创建对应的配置类:
using System.Configuration;
using System.Collections.Generic;
using System.Linq;

namespace YourNamespace
{
    public class ByteListSection : ConfigurationSection
    {
        [ConfigurationProperty("byteLists", IsDefaultCollection = false)]
        public ByteElementCollection ByteLists
        {
            get { return (ByteElementCollection)this["byteLists"]; }
            set { this["byteLists"] = value; }
        }
    }

    [ConfigurationCollection(typeof(ByteElement), AddItemName = "add")]
    public class ByteElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ByteElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ByteElement)element).Value;
        }

        // 将配置项转换为byte数组列表
        public List<byte[]> ToByteList()
        {
            var list = new List<byte[]>();
            foreach (ByteElement elem in this)
            {
                // 把十六进制字符串转成byte数组
                byte[] bytes = Enumerable.Range(0, elem.Value.Length)
                                         .Where(x => x % 2 == 0)
                                         .Select(x => Convert.ToByte(elem.Value.Substring(x, 2), 16))
                                         .ToArray();
                list.Add(bytes);
            }
            return list;
        }
    }

    public class ByteElement : ConfigurationElement
    {
        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get { return (string)this["value"]; }
            set { this["value"] = value; }
        }
    }
}
  1. 读写配置并保存修改:
// 加载配置文件
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var byteSection = (ByteListSection)config.GetSection("byteListSettings");
var myByteLists = byteSection.ByteLists.ToByteList();

// 添加新的byte数组(先转为十六进制字符串)
var newBytes = new byte[] { 0x07, 0x08, 0x09 };
string hexString = BitConverter.ToString(newBytes).Replace("-", "");
var newElem = new ByteElement { Value = hexString };
byteSection.ByteLists.Add(newElem);

// 保存配置修改到文件
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("byteListSettings");

这种方式的优势是配置与应用程序绑定,但读写逻辑相对繁琐,且需要将byte数组转为十六进制字符串存储(配置文件无法直接保存二进制数据)。


内容的提问来源于stack exchange,提问作者xxxkillergamingfortnite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:05:22