C# 讀寫XML文件(XML Helper)

在項目中哪個類只要using XmlManager類的Mynamespace就可以XmlManager.Instance.LoadXml<UserClass>(fullPath)調用。

 XML讀寫類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using System.Dynamic;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;

namespace Mynamespace
{
    public class XmlManager : Singleton<XmlManager>
    {
        public void SaveXml<T>(T obj, String path) 
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            using (StreamWriter writer = new StreamWriter(path))
            {
                serializer.Serialize(writer, obj, ns);
            }
        }

        public T LoadXml<T>(String path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            try
            {
                using (StreamReader reader = new StreamReader(path))
                {
                    if (reader == null)
                        return default(T);

                    T obj = (T)serializer.Deserialize(reader);
                    reader.Close();

                    return obj;
                }
            }
            catch
            {
                return default(T);
            }
        }
    }
}

 Singleton類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mynamespace
{
    public class Singleton<T> where T : class, new()
    {
        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章