c#将对象保存到本地以及读取,xml文件储存与读取

将对象保存到指定路径中,及读取方法

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace TiianmaoShop
{
    /// <summary>
    /// 文件操作工厂
    /// </summary>
    public class FFactory
    {


        /// <summary>
        /// 将对象保存到指定路径中,
        /// 注:因为要保的是对象,所以要在保存的类前面要加上序列化[Serializable],
        /// 序列化:就是把一个整体打散成若干个颗粒
        /// 如:
        /// [Serializable]
        /// public class Goods
        /// {
        /// }
        /// </summary>
        /// <param name="path">要保存的路径,如:C:\a.obj,a.obj是自己的取的文件名和扩展名,可以随便取,没有的路径都会自动生成</param>
        /// 注:路径可以随便写,会自动生成:如:C:\A\B\C\test.obj 程序会自动生成A,B,C目录
        /// <param name="obj">要保存的对象,object:所有类的父基类</param>
        public static void SaveObject(string path,object obj)
        {
            IFormatter formatter = new BinaryFormatter();
            try
            {
            Stream stream = new FileStream(@"" + path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, obj);
                stream.Close();
                Console.WriteLine("[" + path + "]文件保存成功...");
                //将对象写入到本地
            }
            catch (Exception)
            {
                Console.WriteLine("[" + path + "]文件保存失败...");
            }
            
        }
        /// <summary>
        /// 从指定的路径中取出文件,返回指定的类型
        /// T:是指泛型
        /// Read<Hero>那么所有的T都会被换成Hero类
        /// 如:Hero h = FFactory.Read<Hero>("C:\hero.obj");
        /// </summary>
        /// <typeparam name="T">返回指定的类型</typeparam>
        /// <param name="path">文件的路径</param>
        /// <returns></returns>
        /// 





        public static T ReadObject<T>(string path)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(@"" + path, FileMode.Open, FileAccess.Read, FileShare.None);
                T myObj = (T)formatter.Deserialize(stream);
                stream.Close();
                return myObj;
            }
            catch (Exception)
            {
                if (File.Exists(path))//如果文件不存在,创建文件
                {
                }
                else
                {
                    File.Create(path).Dispose();
                }
            }
            //catch 

            T t =default(T);
            return t;
        }
        /// <summary>
        /// 将一个字符串内容写入到指定的目录文件中
        /// </summary>
        /// <param name="path">要写入的目录包括文件名</param>
        /// <param name="content">要写入的内容</param>
        /// <param name="append">是否要追加还是覆盖</param>
        public static void SaveText(string path,string content,bool append = false)
        {
            if (append)
            {
                //追加到原来内容的后面
                File.AppendAllText(path, content);
            }
            else
            {
                //覆盖原来的内容
                File.WriteAllText(path, content);
            }
        }
        /// <summary>
        /// 从指定的目录中读取文件内容
        /// </summary>
        /// <param name="path">要读取的目录</param>
        /// <returns></returns>
        public static string ReadText(string path)
        {
            string str =  File.ReadAllText(path);
            return str;
        }
    }
}

读取xml,保存

public static Dictionary<int,goods> readXML(string url)
        {
            XElement xe = XElement.Load(url);
            var elements = from ele in xe.Elements()
                           select ele;

            Dictionary<int,goods> dictionary = new Dictionary<int, goods>();

            foreach (var ele in elements)
            {
               int  GoodsId = Convert.ToInt32(ele.Attribute("id").Value);
               string GoodsName = ele.Element("name").Value;
                int GoodsStock = Convert.ToInt32(ele.Element("stock").Value);
               int  GoodsPrice = Convert.ToInt32(ele.Element("price").Value);
                goods goods = new goods(GoodsId,GoodsName,GoodsPrice,GoodsStock );
                dictionary.Add(goods.Id, goods);
            }
            return dictionary;
        }
        /// <summary>
        /// 根据id修改XML文件
        /// </summary>
        /// <param name="url">要修改的目录文件路径</param>
        /// <param name="id">商品编号</param>
        /// <param name="list">商品信息</param>
        public static void change(string url, int id, Dictionary<int, goods> dictionary)
        {
            XElement xe = XElement.Load(@url);
            //int goodID = id;
            var elements = from ele in xe.Elements()
                           where (string)ele.Attribute("id") == id + ""
                           select ele;
            if (elements.Count() > 0)
            {

                XElement first = elements.First();
                ///设置新的属性
                first.SetAttributeValue("id", id);
                ///替换新的节点
                first.ReplaceNodes(
                         new XElement("name", dictionary[id].Name),
                         new XElement("stock", dictionary[id].Number),
                         new XElement("price", dictionary[id].Money)
                         );
            }
            xe.Save(@url);
            Console.WriteLine("修改成功!");
        }

XML格式:

<?xml version="1.0" encoding="utf-8"?>
<Phones>
  <!--记录手机的信息-->
  <phone id="1011">
    <name>OPPOFindX</name>
    <stock>50</stock>
    <price>4000</price>
  </phone>
  <phone id="1022">
    <name>iphoneX</name>
    <stock>50</stock>
    <price>6000</price>
  </phone>
  <phone id="1033">
    <name>小米9</name>
    <stock>50</stock>
    <price>3000</price>
  </phone>
  <phone id="1044">
    <name>华为P30</name>
    <stock>50</stock>
    <price>7000</price>
  </phone>
</Phones>
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值