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
{
    /// 
    /// 文件操作工厂
    /// 
    public class FFactory
    {


        /// 
        /// 将对象保存到指定路径中,
        /// 注:因为要保的是对象,所以要在保存的类前面要加上序列化[Serializable],
        /// 序列化:就是把一个整体打散成若干个颗粒
        /// 如:
        /// [Serializable]
        /// public class Goods
        /// {
        /// }
        /// 
        /// 要保存的路径,如:C:\a.obj,a.obj是自己的取的文件名和扩展名,可以随便取,没有的路径都会自动生成
        /// 注:路径可以随便写,会自动生成:如:C:\A\B\C\test.obj 程序会自动生成A,B,C目录
        /// 要保存的对象,object:所有类的父基类
        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 + "]文件保存失败...");
            }
            
        }
        /// 
        /// 从指定的路径中取出文件,返回指定的类型
        /// T:是指泛型
        /// Read那么所有的T都会被换成Hero类
        /// 如:Hero h = FFactory.Read("C:\hero.obj");
        /// 
        /// 返回指定的类型
        /// 文件的路径
        /// 
        /// 





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

读取xml,保存

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

            Dictionary dictionary = new Dictionary();

            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;
        }
        /// 
        /// 根据id修改XML文件
        /// 
        /// 要修改的目录文件路径
        /// 商品编号
        /// 商品信息
        public static void change(string url, int id, Dictionary 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格式:



  
  
    OPPOFindX
    50
    4000
  
  
    iphoneX
    50
    6000
  
  
    小米9
    50
    3000
  
  
    华为P30
    50
    7000
  

你可能感兴趣的:(c#)