-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serialization.cs
77 lines (65 loc) · 2.02 KB
/
Serialization.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
75
76
77
/**********************************************************************/
/* Copyright (c) 2023 Carpe Diem Software Developing by Alex Versetty */
/* http://carpediem.0fees.us */
/**********************************************************************/
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace CDSD.Data
{
class Serialization
{
public static string XmlSerialize<T>(T value)
{
if (value == null) {
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false);
settings.Indent = true;
settings.IndentChars = " ";
settings.OmitXmlDeclaration = false;
settings.NewLineHandling = NewLineHandling.Entitize;
using (StringWriter textWriter = new StringWriter()) {
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
public static T XmlDeserialize<T>(string xml)
{
if (string.IsNullOrEmpty(xml)) {
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml)) {
using (XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
return (T)serializer.Deserialize(xmlReader);
}
}
}
public static byte[] BinSerialize(object value)
{
if (value == null) {
return null;
}
byte[] bytes;
var formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream()) {
formatter.Serialize(stream, value);
bytes = stream.ToArray();
}
return bytes;
}
public static object BinDeserialize(byte[] bytes)
{
var formatter = new BinaryFormatter();
return formatter.Deserialize(new MemoryStream(bytes));
}
}
}