markus / ConvertService / ServiceBase / Markus.Service.Extensions / Helper / SerializableHelper.cs @ e6e06e16
이력 | 보기 | 이력해설 | 다운로드 (1.75 KB)
1 | 53c9637d | taeseongkim | using System; |
---|---|---|---|
2 | using System.Collections.Generic; |
||
3 | using System.IO; |
||
4 | using System.Linq; |
||
5 | using System.Runtime.Serialization; |
||
6 | using System.Runtime.Serialization.Formatters.Binary; |
||
7 | using System.Text; |
||
8 | using System.Threading.Tasks; |
||
9 | |||
10 | namespace Markus.Service.Helper |
||
11 | { |
||
12 | public static class SerializableHelper |
||
13 | { |
||
14 | private static readonly BinaryFormatter Formatter = new BinaryFormatter(); |
||
15 | |||
16 | public static byte[] Serialize(object toSerialize) |
||
17 | { |
||
18 | byte[] result = new byte[0]; |
||
19 | |||
20 | try |
||
21 | { |
||
22 | using (var stream = new MemoryStream()) |
||
23 | { |
||
24 | Formatter.Serialize(stream, toSerialize); |
||
25 | var array = stream.ToArray(); |
||
26 | |||
27 | if(array.Length > 0) |
||
28 | { |
||
29 | result = array; |
||
30 | } |
||
31 | } |
||
32 | } |
||
33 | catch (Exception ex) |
||
34 | { |
||
35 | throw new Exception("SerializableHelper Serialize Convert error",ex); |
||
36 | } |
||
37 | |||
38 | return result; |
||
39 | } |
||
40 | |||
41 | public static T Deserialize<T>(byte[] serialized) |
||
42 | { |
||
43 | try |
||
44 | { |
||
45 | if (serialized?.Length > 0) |
||
46 | { |
||
47 | |||
48 | using (var stream = new MemoryStream(serialized)) |
||
49 | { |
||
50 | var result = (T)Formatter.Deserialize(stream); |
||
51 | return result; |
||
52 | } |
||
53 | } |
||
54 | else |
||
55 | { |
||
56 | throw new Exception("Deserialize<T> serialized Target is null or zero."); |
||
57 | } |
||
58 | } |
||
59 | catch (Exception ex) |
||
60 | { |
||
61 | throw new Exception("SerializableHelper Deserialize error",ex); |
||
62 | } |
||
63 | } |
||
64 | } |
||
65 | } |