From 41ad37b3bb7acfd06a586af420e8f063f4fe6cb0 Mon Sep 17 00:00:00 2001 From: Andrei Tudor Date: Sat, 5 Aug 2023 21:25:47 +0300 Subject: [PATCH] Fixed a bug when loading empty json file --- PluginManager/Others/JsonManager.cs | 2 +- PluginManager/Others/SettingsDictionary.cs | 42 +++++++++++++++------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/PluginManager/Others/JsonManager.cs b/PluginManager/Others/JsonManager.cs index ea3576a..1950346 100644 --- a/PluginManager/Others/JsonManager.cs +++ b/PluginManager/Others/JsonManager.cs @@ -32,13 +32,13 @@ public class JsonManager /// public static async Task ConvertFromJson(string input) { - Console.WriteLine(input); Stream text; if (File.Exists(input)) text = new MemoryStream(await File.ReadAllBytesAsync(input)); else text = new MemoryStream(Encoding.ASCII.GetBytes(input)); text.Position = 0; + var obj = await JsonSerializer.DeserializeAsync(text); await text.FlushAsync(); text.Close(); diff --git a/PluginManager/Others/SettingsDictionary.cs b/PluginManager/Others/SettingsDictionary.cs index faac195..86b95a3 100644 --- a/PluginManager/Others/SettingsDictionary.cs +++ b/PluginManager/Others/SettingsDictionary.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; @@ -7,31 +8,46 @@ namespace PluginManager.Others; public class SettingsDictionary : IDictionary { - public string _file { get; set; } + public string? _file { get; } private IDictionary? _dictionary; - public SettingsDictionary(string file) + public SettingsDictionary(string? file) { - if (file is null) - throw new FileLoadException("The file can not be null"); - - if (!File.Exists(file)) - File.Create(file).Close(); - _file = file; - LoadFromFile(); + if (!LoadFromFile()) + { + throw new Exception($"Failed to load {file}. Please check the file and try again."); + } } - + public async Task SaveToFile() { if (!string.IsNullOrEmpty(_file)) await JsonManager.SaveToJsonFile(_file, _dictionary); } - private void LoadFromFile() + private bool LoadFromFile() { if (!string.IsNullOrEmpty(_file)) - _dictionary = JsonManager.ConvertFromJson>(_file).Result; + try + { + if (File.Exists(_file)){ + if (!File.ReadAllText(_file).Contains('{') && !File.ReadAllText(_file).Contains('}')) + File.WriteAllText(_file, "{}"); + } + else + File.WriteAllText(_file, "{}"); + _dictionary = JsonManager.ConvertFromJson>(_file).Result; + return true; + } + catch (Exception e) + { + Config.Logger.Error(e); + return false; + } + + return false; + } public IEnumerator> GetEnumerator()