目录
介绍
对于任何类型的软件来说,保存到键值文件都是一个简单而有用的操作,尽管根据我的经验,您在检索此信息时很容易遇到敏捷性问题。
使用此类,您可以毫不费力地查看、创建、修改键。使用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