Fixed a bug when loading empty json file

This commit is contained in:
2023-08-05 21:25:47 +03:00
parent 0104d09509
commit 41ad37b3bb
2 changed files with 30 additions and 14 deletions

View File

@@ -32,13 +32,13 @@ public class JsonManager
/// <returns></returns> /// <returns></returns>
public static async Task<T> ConvertFromJson<T>(string input) public static async Task<T> ConvertFromJson<T>(string input)
{ {
Console.WriteLine(input);
Stream text; Stream text;
if (File.Exists(input)) if (File.Exists(input))
text = new MemoryStream(await File.ReadAllBytesAsync(input)); text = new MemoryStream(await File.ReadAllBytesAsync(input));
else else
text = new MemoryStream(Encoding.ASCII.GetBytes(input)); text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0; text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text); var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync(); await text.FlushAsync();
text.Close(); text.Close();

View File

@@ -1,4 +1,5 @@
using System.Collections; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -7,19 +8,16 @@ namespace PluginManager.Others;
public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue> public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{ {
public string _file { get; set; } public string? _file { get; }
private IDictionary<TKey, TValue>? _dictionary; private IDictionary<TKey, TValue>? _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; _file = file;
LoadFromFile(); if (!LoadFromFile())
{
throw new Exception($"Failed to load {file}. Please check the file and try again.");
}
} }
public async Task SaveToFile() public async Task SaveToFile()
@@ -28,10 +26,28 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
await JsonManager.SaveToJsonFile(_file, _dictionary); await JsonManager.SaveToJsonFile(_file, _dictionary);
} }
private void LoadFromFile() private bool LoadFromFile()
{ {
if (!string.IsNullOrEmpty(_file)) if (!string.IsNullOrEmpty(_file))
try
{
if (File.Exists(_file)){
if (!File.ReadAllText(_file).Contains('{') && !File.ReadAllText(_file).Contains('}'))
File.WriteAllText(_file, "{}");
}
else
File.WriteAllText(_file, "{}");
_dictionary = JsonManager.ConvertFromJson<IDictionary<TKey, TValue>>(_file).Result; _dictionary = JsonManager.ConvertFromJson<IDictionary<TKey, TValue>>(_file).Result;
return true;
}
catch (Exception e)
{
Config.Logger.Error(e);
return false;
}
return false;
} }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()