프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / ConvertService / ServiceController / Markus.Service.Extensions / Helper / SerializableHelper.cs @ 5c387707

이력 | 보기 | 이력해설 | 다운로드 (1.75 KB)

1
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
}
클립보드 이미지 추가 (최대 크기: 500 MB)