C# 使用SnsSharp读写xml文件

https://download.csdn.net/download/sns1991sns/88041637

gitee下载地址:https://gitee.com/linsns/snssharp

使用举例:

    Data data = new Data();
    //写入
    XmlFile.Write("7.xml", data);
    //读取
    data=XmlFile.Read<Data>("7.xml");


    其中Data是存储数据的可序列的类
    [Serializable]
    class Data
    {
        public int a;
        public int b;
        public int c;
    }

 其中XmlFile类源码如下: 

    public static class XmlFile
    {
        /// <summary>
        /// 根据传入的文件全路径读取文件,注:类的访问修饰符必须是:public
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="filePath">文件全路径</param>
        /// <returns></returns>
        public static T Read<T>(string filePath)
        {
            object obj;
            try
            {
                using (FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    XmlSerializer serial = new XmlSerializer(typeof(T));
                    obj = serial.Deserialize(reader);
                }
            }
            catch(Exception ex)
            {
                obj = null;
            }
            return (T)obj;
        }

        /// <summary>
        /// 传入文件全路径,将数据结构保存为文件
        /// </summary>
        /// <param name="filePath">文件全路径</param>
        /// <param name="obj">要保存为文件的数据结构</param>
        public static void Write(string filePath, object obj)
        {
            try
            {
                FileInfo info = new FileInfo(filePath);
                if (info.Exists) info.Attributes = FileAttributes.Normal;
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    if (obj!=null)
                    {
                        Type tempType = obj.GetType();
                        XmlSerializer serial = new XmlSerializer(tempType);
                        serial.Serialize(writer, obj);
                    }
                }
            }
            catch(Exception) { }
        }
    }

技术交流

QQ群: 577276243

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇云雨巷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值