-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileCache.cs
64 lines (59 loc) · 2.24 KB
/
FileCache.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
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace MFramework.Common
{
public static class FileCache
{
/// <summary>
/// Deserializes a data file into an object of type {T}.
/// </summary>
/// <typeparam name = "T">Type of object to deseralize and return.</typeparam>
/// <param name = "path">Full path to file containing seralized data.</param>
/// <returns>If object is successfully deseralized, the object of type {T},
/// otherwise null.</returns>
/// <exception cref = "ArgumentNullException">Thrown if the path parameter is null or empty.</exception>
public static T RetrieveFromCache<T>(string path) where T : class
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
try
{
using (var file = File.Open(path, FileMode.Open))
{
var bf = new BinaryFormatter();
return bf.Deserialize(file) as T;
}
}
catch
{
// Return null if the object can't be deseralized
return null;
}
}
/// <summary>
/// Serialize the given object of type {T} to a file at the given path.
/// </summary>
/// <typeparam name = "T">Type of object to serialize.</typeparam>
/// <param name = "obj">Object to serialize and store in a file.</param>
/// <param name = "path">Full path of file to store the serialized data.</param>
/// <exception cref = "ArgumentNullException">Thrown if obj or path parameters are null.</exception>
public static void StoreInCache<T>(T obj, string path) where T : class
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
using (var file = File.Open(path, FileMode.Create))
{
new BinaryFormatter().Serialize(file, obj);
}
}
}
}