class XMLStorage XmlSerializer xmlser String filePath private XMLStora

 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
75
76
class XMLStorage <T>
{
XmlSerializer xmlser;
String filePath;
private XMLStorage(){
}
public XMLStorage(string fileName)
{
xmlser = new XmlSerializer(typeof(T));
filePath = System.Environment.CurrentDirectory + "\\" + fileName + ".xml";
}
public XMLStorage(string fileName, Type[] typeArr)
{ xmlser = new XmlSerializer(typeof(T), typeArr);
filePath = System.Environment.CurrentDirectory + "\\" + fileName + ".xml";
}
public int SerializeObject(T obj)
{
int retVal = 0;
FileStream file = new FileStream(filePath, FileMode.OpenOrCreate);
try
{
xmlser.Serialize(file, obj);
}
catch (InvalidOperationException ex)
{
GUITools.MessageBoxes.ExclamationBox(ex.Message, "Ошибка");
retVal = -1;
}
catch (Exception ex)
{
GUITools.MessageBoxes.ExclamationBox(ex.Message, "Ошибка");
retVal = -1;
}
finally
{
file.Close();
}
return retVal;
}
public int DeserializeObject(ref T obj)
{
int retVal = 0;
FileStream file = null;
try
{
file = new FileStream(filePath, FileMode.Open);
obj = (T)xmlser.Deserialize(file);
}
catch (InvalidOperationException ex)
{
GUITools.MessageBoxes.ExclamationBox(ex.Message, "Ошибка");
retVal = -1;
}
catch(FileNotFoundException)
{
return -1;
}
catch (Exception ex)
{
GUITools.MessageBoxes.ExclamationBox(ex.Message, "Ошибка");
retVal = -1;
}
finally
{
if(file != null)
file.Close();
}
return retVal;
}