forked from royosherove/dotnet-perfplus
/
SelfSerializer.cs
74 lines (68 loc) · 1.96 KB
/
SelfSerializer.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
72
73
74
using System;
using System.IO;
using System.Xml.Serialization;
using System.Web;
namespace SysMonitor
{
/// <summary>
/// Summary description for SelfSerializer.
/// This class is taken from Matthew Reynolds great article on
/// CSharpToday: http://www.csharptoday.com/content.asp?id=1763
/// </summary>
[Serializable()]
public class SelfSerializer
{
public SelfSerializer()
{
}
// Load - we don't know the class, so we need that...
public static object Load(string filename,Type type)
{
// file...
FileStream stream = null;
try
{
// open the stream...
stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
XmlSerializer serializer = new XmlSerializer(type);
return serializer.Deserialize(stream);
}
finally
{
if (stream != null)
stream.Close();
}
}
// Save - save the file to disk...
public virtual void Save(string filename)
{
// file...
FileStream stream = null;
try
{
// open...
stream = new FileStream(filename, FileMode.Create);
Save(stream);
}
finally
{
if (stream != null)
stream.Close();
}
}
public void Save(Stream stream)
{
// serialize it...
try
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stream, this);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}