-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathIsolatedStorageExtensions.cs
More file actions
60 lines (57 loc) · 2.13 KB
/
IsolatedStorageExtensions.cs
File metadata and controls
60 lines (57 loc) · 2.13 KB
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
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization.Formatters.Binary;
namespace CabMaker
{
/// <summary>
/// Extension methods for working with isolated storage.
/// </summary>
public static class IsolatedStorageExtensions
{
/// <summary>
/// Saves an object to isolated storage.
/// </summary>
/// <param name="isoStorage">Isolated storage</param>
/// <param name="obj">Object to save</param>
/// <param name="fileName">File name to which object will be saved</param>
public static void SaveObject(this IsolatedStorage isoStorage, object obj, string fileName)
{
using (IsolatedStorageFileStream writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(writeStream, obj);
}
}
/// <summary>
/// Reads an object from isolated storage.
/// </summary>
/// <typeparam name="T">Type of object to read</typeparam>
/// <param name="isoStorage">Isolated storage</param>
/// <param name="fileName">File name from which object will be loaded</param>
/// <returns>Object read from isolated storage (as type <typeparamref name="T"/>)</returns>
public static T LoadObject<T>(this IsolatedStorage isoStorage, string fileName)
{
try
{
using (IsolatedStorageFileStream readStream = new IsolatedStorageFileStream(fileName, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
T readData = (T)formatter.Deserialize(readStream);
return readData;
}
catch
{
return default(T);
}
}
}
catch (FileNotFoundException)
{
return default(T);
}
}
}
}