将设置保存在JSON文件中,并使用LINQ进行读取和保存

该文章介绍了一个C#类,用于在JSON文件中保存和检索键值对。通过使用LINQ和Newtonsoft.Json库,可以轻松创建、修改和查询这些设置。类支持添加新键、更新值、删除键以及检查键是否存在,适合小型本地存储需求。
摘要由CSDN通过智能技术生成

目录

介绍

背景

使用代码

兴趣点


介绍

对于任何类型的软件来说,保存到键值文件都是一个简单而有用的操作,尽管根据我的经验,您在检索此信息时很容易遇到敏捷性问题。

使用此类,您可以毫不费力地查看、创建、修改键。使用LINQ(世界奇迹之一),您可以搜索特定键或显示所有键。

对于任何开始编写代码的人来说,这都是福音。

背景

您可以将这个简单的类添加到您的项目中,并立即开始将信息保存到Json格式文件中,用任何扩展名伪装它。

插入此类后,需要使用简单的CTRL+包含Newtonsoft.Json nuget库。
然后,使用Linq并且只需很少的努力,您就可以逐个或一次读取所有信息。

使用代码

因此,让我们开始:在我们的项目中,我们插入一个新类:

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
 
namespace SettingsFileClass
{
    public class SettingsInJsonFile
      {
          // Here you have to set the network path where you want to insert the file
          // For example you can use c:\MyTestApp\Settings.ini
          //                         c:\program files\MyTestApplication\MainConfig.config
          // Or you can use Isolated storage for location your file
          public const string FilePath = @"D:\temp\settings.json";
          // You can choose if you prefer idented or none (more space saving)
          public const Formatting MyFormatting = Formatting.Indented;
 
 
          /// <summary>
          /// Class Settings
          /// </summary>
          internal string _key;
          public string Key { get { return _key; } set { _key = value.ToUpper(); } }
          public string? Value { get; set; }
 
          /// <summary>
          /// Set a new value in a Key if exist. You can use for create a new key using
          /// Optional value (by default return false if Key not exist
          /// </summary>
          /// <param name="Key">This string will be saved only uppercase</param>
          /// <param name="NewValue">New value in string type</param>
          /// <param name="CreateIfNew">bool true = create, false = not create</param>
          /// <returns></returns>
          internal static bool Set(string Key, string NewValue, bool CreateIfNew = false)
          {
              Key = Key.ToUpper();
              var Item = GetObject(Key);
              var _data = GetAll().ToList();
 
              if (Item == null)
              {
                  //Nof found -> user choise if create
                  if (CreateIfNew)
                  {
                      //Add new key in Data Items
                      _data.Add(new SettingsInJsonFile()
                      {
                          Key = Key,
                          Value = NewValue
                      });
 
                  }
                  else
                  {
                      //Not found, not allow to create
                      return false;
                  }
              }
              else
                  _data.First(x => x.Key == Key).Value = NewValue; //Update value
 
              string json = JsonConvert.SerializeObject(_data.ToArray(), MyFormatting);
              //write string to destination
              File.WriteAllText(FilePath, json);
 
              return true;
          }
          internal static bool Delete(string KeyToDelete)
          {
              if (Exist(KeyToDelete))
              {
                  var _data = GetAll().Where(x => x.Key != KeyToDelete.ToUpper()).ToArray();
                  string json = JsonConvert.SerializeObject(_data, MyFormatting);
 
                  //write string to destination
                  File.WriteAllText(FilePath, json);
 
                  return true;
              }
              return false;
          }
          internal static List<SettingsInJsonFile> GetAll()
          {
              //Create file Settings if not exists
              if (!File.Exists(FilePath))
              {
                  //Creation of new file with Inizialization ->"[]"
                  using StreamWriter wr = File.CreateText(FilePath);
                  wr.WriteLine("[]");
              }
 
              using StreamReader r = new(FilePath);
              string json = r.ReadToEnd();
              if (string.IsNullOrEmpty(json)) json = "[]";
              var Response = JsonConvert.DeserializeObject<List<SettingsInJsonFile>>(json);
              return Response;
          }
 
          internal static string GetValue(string Key) => GetAll().FirstOrDefault(x => x.Key == Key.ToUpper()).Value;
          internal static SettingsInJsonFile? GetObject(string Key) => GetAll().FirstOrDefault(x => x.Key == Key.ToUpper());
          internal static bool Exist(string Key) => GetAll().FirstOrDefault(x => x.Key == Key.ToUpper()) != null;
 
      }
}

例如,文件中的文件结果是:

[
    {"Key":"key","Value":"07/10/2022 13:04:21"},
    {"Key":"backcolor","Value":"#FFFFFF"}
    {"Key":"forecolor","Value":"#000000"}
]

兴趣点

这个简单的类对于用于本地存储的小型文本文件来说足够强大。对于更复杂的场景或变量数量开始呈指数增长的情况,我不建议使用它。

函数CREATE创建键,但此键是Keysensitive,因此要添加的一个很好的检查是仅将所有键创建为大写。

https://www.codeproject.com/Tips/5293960/Save-Your-Settings-in-a-File-in-JSON-and-using-LIN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值