啊鑫
2024-07-11 afbf8700d137710713db61955879d0f5acb73738
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
#region
 
using System;
using System.IO;
using System.Xml.Serialization;
 
#endregion
 
namespace CSFrameworkV5.Common
{
    /// <summary>
    ///     对象序列化
    /// </summary>
    public class ObjectSerializer
    {
        /// <summary>
        ///     读取XML文件,反序列化为对象实例
        /// </summary>
        /// <param name="objectType">指定对象类型</param>
        /// <param name="file">文件名</param>
        /// <returns>对象实例</returns>
        public static object Deserialize(Type objectType, string file)
        {
            object o = null;
            Stream stream = null;
            try
            {
                if (File.Exists(file))
                {
                    var xs = new XmlSerializer(objectType);
                    stream = new FileStream(file, FileMode.Open,
                        FileAccess.Read, FileShare.ReadWrite);
                    o = xs.Deserialize(stream);
                    stream.Close();
                    stream = null;
                }
 
                return o;
            }
            catch
            {
                if (stream != null) stream.Close();
 
                return o;
            }
        }
 
        /// <summary>
        ///     将对象写入XML文件
        /// </summary>
        /// <param name="o">对象实例</param>
        /// <param name="file">文件名</param>
        public static void SerializeObject(object o, string file)
        {
            Stream stream = null;
            try
            {
                var xs = new XmlSerializer(o.GetType());
                stream = new FileStream(file, FileMode.Create, FileAccess.Write,
                    FileShare.ReadWrite);
                xs.Serialize(stream, o);
                stream.Flush();
                stream.Close();
                stream = null;
            }
            catch
            {
                if (stream != null) stream.Close();
            }
        }
    }
}