-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSerializer.cs
71 lines (62 loc) · 2.66 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#if SFML
using FrameworkColor = SFML.Graphics.Color;
using FrameworkPoint = SFML.System.Vector2i;
using FrameworkRect = SFML.Graphics.IntRect;
#elif MONOGAME
using FrameworkColor = Microsoft.Xna.Framework.Color;
using FrameworkPoint = Microsoft.Xna.Framework.Point;
using FrameworkRect = Microsoft.Xna.Framework.Rectangle;
using FrameworkSpriteEffect = Microsoft.Xna.Framework.Graphics.SpriteEffects;
#endif
namespace SadConsole
{
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Common serialization tasks for SadConsole.
/// </summary>
public static partial class Serializer
{
/// <summary>
/// Serializes the <paramref name="instance"/> instance to the specified file.
/// </summary>
/// <typeparam name="T">Type of object to serialize</typeparam>
/// <param name="instance">The object to serialize.</param>
/// <param name="file">The file to save the object to.</param>
/// <param name="knownTypes">Optional list of known types for serialization.</param>
public static void Save<T>(T instance, string file, IEnumerable<Type> knownTypes = null)
{
if (System.IO.File.Exists(file))
System.IO.File.Delete(file);
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T), knownTypes);
using (var stream = System.IO.File.OpenWrite(file))
serializer.WriteObject(stream, instance);
}
/// <summary>
/// Deserializes a new instance of <typeparamref name="T"/> from the specified file.
/// </summary>
/// <typeparam name="T">The type of object to deserialize.</typeparam>
/// <param name="file">The file to load from.</param>
/// <param name="knownTypes">Known types used during deserialization.</param>
/// <returns>A new object instance.</returns>
public static T Load<T>(string file, IEnumerable<Type> knownTypes = null)
{
if (System.IO.File.Exists(file))
{
using (var fileObject = System.IO.File.OpenRead(file))
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T), knownTypes);
return (T)serializer.ReadObject(fileObject);
}
}
throw new System.IO.FileNotFoundException("File not found.", file);
}
}
}