source: binary-improvements/7dtd-server-fixes/src/PersistentData/PersistentContainer.cs@ 488

Last change on this file since 488 was 455, checked in by alloc, 16 months ago

25_30_44

  • Got rid (mostly) of custom JSON serialization
  • Some code cleanup
File size: 1.6 KB
Line 
1using System;
2using System.IO;
3using System.Runtime.Serialization;
4using System.Runtime.Serialization.Formatters.Binary;
5
6namespace AllocsFixes.PersistentData {
7 [Serializable]
8 public class PersistentContainer {
9 private const string persistentDataFileName = "/AllocsPersistentData.bin";
10
11 private Players players;
12 [OptionalField] private Attributes attributes;
13
14 public Players Players => players ??= new Players ();
15
16 public Attributes Attributes => attributes ??= new Attributes ();
17
18 private static PersistentContainer instance;
19
20 public static PersistentContainer Instance => instance ??= new PersistentContainer ();
21
22 private PersistentContainer () {
23 }
24
25 public void Save () {
26 lock (fileLockObject) {
27 using Stream stream = File.Open ($"{GameIO.GetSaveGameDir ()}{persistentDataFileName}", FileMode.Create);
28 BinaryFormatter bFormatter = new BinaryFormatter ();
29 bFormatter.Serialize (stream, this);
30 }
31 }
32
33 public static bool Load () {
34 var filePath = $"{GameIO.GetSaveGameDir ()}{persistentDataFileName}";
35
36 if (!File.Exists (filePath)) {
37 return false;
38 }
39
40 try {
41 PersistentContainer obj;
42 lock (fileLockObject) {
43 using Stream stream = File.Open (filePath, FileMode.Open);
44 BinaryFormatter bFormatter = new BinaryFormatter ();
45 obj = (PersistentContainer)bFormatter.Deserialize (stream);
46 }
47
48 instance = obj;
49 return true;
50 } catch (Exception e) {
51 Log.Error ("Exception in PersistentContainer.Load");
52 Log.Exception (e);
53 }
54
55 return false;
56 }
57
58 private static readonly object fileLockObject = new();
59 }
60}
Note: See TracBrowser for help on using the repository browser.