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>
public static async Task<T> ConvertFromJson<T>(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<T>(text);
await text.FlushAsync();
text.Close();

View File

@@ -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<TKey, TValue> : IDictionary<TKey, TValue>
{
public string _file { get; set; }
public string? _file { get; }
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;
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<IDictionary<TKey, TValue>>(_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<IDictionary<TKey, TValue>>(_file).Result;
return true;
}
catch (Exception e)
{
Config.Logger.Error(e);
return false;
}
return false;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()