-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serializer.cs
51 lines (43 loc) · 1.54 KB
/
Serializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Newtonsoft.Json;
using System;
using System.IO;
namespace In_Game_Chat
{
internal class Serializer
{
public static T LoadFromFile<T>(string filePath) where T : class
{
if (!IsPathValid(filePath))
return null;
string json = File.ReadAllText(filePath);
if (String.IsNullOrEmpty(json))
return null;
return JsonConvert.DeserializeObject<T>(json);
}
private static bool IsPathValid(string filePath)
{
Guard.ThrowIfStringIsNull(filePath, "Can't load file, path is null");
if (!File.Exists(filePath))
return false;
return true;
}
/// <summary>
/// Save any class to file. This is not done yet
/// </summary>
public static void SaveToFile<T>(T jsonObject, string savePath, bool overwriteExisting = true) where T : class
{
Guard.ThrowIfStringIsNull(savePath, "Can't save file, save path is null");
CreateDirIfNotFound(savePath);
string json = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
bool keepOriginal = !overwriteExisting;
StreamWriter serialize = new StreamWriter(savePath, keepOriginal);
serialize.Write(json);
serialize.Close();
}
private static void CreateDirIfNotFound(string dir)
{
FileInfo f = new FileInfo(dir);
Directory.CreateDirectory(f.Directory.FullName);
}
}
}