xcd
2020-03-29 95d9d4a9d26323c51087a056c25f88180f1e3c45
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
using System;
using System.IO;
using System.Text;
 
namespace ToolKit.FileToolkit
{
    public class SerializeFileTool<T>
    {
        public T GetConfig(string fileName)
        {
            T local = default(T);
            byte[] bStr = null;
            if (this.ReadBytes(fileName, out bStr) == FileOperationResult.OK)
            {
                local = SerializeTool<T>.XmlSerializerDeserialize(bStr);
            }
            return local;
        }
 
        private FileOperationResult ReadBytes(string path, out byte[] bStr)
        {
            bStr = null;
            if (!File.Exists(path))
            {
                return FileOperationResult.NOTEXIST;
            }
            try
            {
                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
                {
                    bStr = new byte[stream.Length];
                    stream.Read(bStr, 0, bStr.Length);
                }
            }
            catch
            {
                return FileOperationResult.WRITEERROR;
            }
            return FileOperationResult.OK;
        }
 
        public void SetConfig(string fileName, T config)
        {
            this.WriteBytes(fileName, FileMode.Create, SerializeTool<T>.XmlSerializerSerialize(config));
        }
 
        private FileOperationResult WriteBytes(string path, FileMode filemode, byte[] bStr)
        {
            try
            {
                using (FileStream stream = new FileStream(path, filemode, FileAccess.ReadWrite))
                {
                    stream.Write(bStr, 0, bStr.Length);
                }
            }
            catch (Exception)
            {
                return FileOperationResult.WRITEERROR;
            }
            return FileOperationResult.OK;
        }
 
        private FileOperationResult WriteString(string path, FileMode filemode, string str)
        {
            byte[] bytes = Encoding.Default.GetBytes(str);
            return this.WriteBytes(path, filemode, bytes);
        }
    }
}