public static T DeserializeDB <T>(string location, bool decryptObject = false) where T : new() { try { string value; using (var reader = new StreamReader(new FileStream(location, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))) { value = reader.ReadToEnd(); if (value != null && value.Length != 0) { if (decryptObject) { value = Cryptor.Decrypt(value); } } else { return(default(T)); } } return(JsonConvert.DeserializeAnonymousType(value, new T())); } catch (Exception e) { Log.Error(dbTag, e.Message); return(default(T)); } }
/// <summary> /// Serializes a json database asynchronously. /// </summary> /// <param name="location">Where to write the database file to</param> /// <param name="objectToSerialize">The database object to write to json</param> /// <param name="encryptObject">Set to true if you want to encrypt the database</param> public static async Task SerializeDBAsync(string location, object objectToSerialize, bool encryptObject = false) { await Task.Run(() => { try { if (objectToSerialize != null) { using (StreamWriter w = new StreamWriter(new FileStream(location, FileMode.Create, FileAccess.ReadWrite, FileShare.None))) { if (encryptObject) { w.Write(Cryptor.Encrypt(JsonConvert.SerializeObject(objectToSerialize))); } else { w.Write(JsonConvert.SerializeObject(objectToSerialize)); } Log.Debug(dbTag, $"Successfully wrote DB at {location}."); } } } catch (Exception e) { Log.Error(dbTag, e.Message); } }); }