首页 > 代码库 > IOSerialize,xml和json,soap序列化器,二进制序列化器,XML序列化器,文件 检查、新增、复制、移动、删除

IOSerialize,xml和json,soap序列化器,二进制序列化器,XML序列化器,文件 检查、新增、复制、移动、删除

1 文件夹/文件 检查、新增、复制、移动、删除,
2 文件读写,记录文本日志/读取配置文件
3 三种序列化器
4 xml和json
1.文件夹/文件 检查、新增、复制、移动、删除,2 文件读写,记录文本日志/读取配置文件

using System.IO;
/// <summary> /// 配置绝对路径 /// </summary> private static string LogPath = ConfigurationManager.AppSettings["LogPath"]; private static string LogMovePath = ConfigurationManager.AppSettings["LogMovePath"]; /// <summary> /// 获取当前程序路径 /// </summary> private static string LogPath2 = AppDomain.CurrentDomain.BaseDirectory;
         DirectoryInfo directory = new DirectoryInfo(LogPath);//不存在不报错  注意exists属性
                directory.FullName;//获取目录或文件的完整目录。
                directory.CreationTime;//获取或设置当前文件或目录的创建时间。
                directory.LastWriteTime;//获取或设置上次写入当前文件或目录的时间。
                Path.Combine(LogPath, "info.txt");// 将两个字符串组合成一个路径。
                FileInfo fileInfo = new FileInfo(Path.Combine(LogPath, "info.txt"));//提供创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 System.IO.FileStream 对象。 此类不能被继承。
                Directory.Exists(LogPath);//检测文件夹是否存在
{//File
                string fileName = Path.Combine(LogPath, "log.txt");
                string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
                string fileNameMove = Path.Combine(LogPath, "logMove.txt");
                bool isExists = File.Exists(fileName);
                if (!isExists)
                {
                    Directory.CreateDirectory(LogPath);
                    using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        string name = "12345567778890";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        fileStream.Write(bytes, 0, bytes.Length);
                        fileStream.Flush();
                    }
                    using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
                    {
                        StreamWriter sw = new StreamWriter(fileStream);
                        sw.WriteLine("1234567890");
                        sw.Flush();
                    }

                    using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string msg = "今天是Course6IOSerialize,今天上课的人有55个人";
                        sw.WriteLine(msg);
                        sw.Flush();
                    }
                    using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
                    {
                        string name = "0987654321";
                        byte[] bytes = Encoding.Default.GetBytes(name);
                        sw.BaseStream.Write(bytes, 0, bytes.Length);
                        sw.Flush();
                    }



                    foreach (string result in File.ReadAllLines(fileName))
                    {
                        Console.WriteLine(result);
                    }
                    string sResult = File.ReadAllText(fileName);
                    Byte[] byteContent = File.ReadAllBytes(fileName);
                    string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);

                    using (FileStream stream = File.OpenRead(fileName))//分批读取
                    {
                        int length = 5;
                        int result = 0;

                        do
                        {
                            byte[] bytes = new byte[length];
                            result = stream.Read(bytes, 0, 5);
                            for (int i = 0; i < result; i++)
                            {
                                Console.WriteLine(bytes[i].ToString());
                            }
                        }
                        while (length == result);
                    }

                    File.Copy(fileName, fileNameCopy);
                    File.Move(fileName, fileNameMove);
                    File.Delete(fileNameCopy);
                    File.Delete(fileNameMove);//尽量不要delete
                }
            }
{//DriveInfo
                DriveInfo[] drives = DriveInfo.GetDrives();

                foreach (DriveInfo drive in drives)
                {
                    if (drive.IsReady)
                        Console.WriteLine("类型:{0} 卷标:{1} 名称:{2} 总空间:{3} 剩余空间:{4}", drive.DriveType, drive.VolumeLabel, drive.Name, drive.TotalSize, drive.TotalFreeSpace);
                    else
                        Console.WriteLine("类型:{0}  is not ready", drive.DriveType);
                }

            }
{
                Console.WriteLine(Path.GetDirectoryName(LogPath));  //返回目录名,需要注意路径末尾是否有反斜杠对结果是有影响的
                Console.WriteLine(Path.GetDirectoryName(@"d:\\abc")); //将返回 d:\
                Console.WriteLine(Path.GetDirectoryName(@"d:\\abc\"));// 将返回 d:\abc
                Console.WriteLine(Path.GetRandomFileName());//将返回随机的文件名
                Console.WriteLine(Path.GetFileNameWithoutExtension("d:\\abc.txt"));// 将返回abc
                Console.WriteLine(Path.GetInvalidPathChars());// 将返回禁止在路径中使用的字符
                Console.WriteLine(Path.GetInvalidFileNameChars());//将返回禁止在文件名中使用的字符
                Console.WriteLine(Path.Combine(LogPath, "log.txt"));//合并两个路径
            }

日志方法

 /// <summary>
        ////// 1  try catch旨在上端使用,保证对用户的展示
        /// 2  下端不要吞掉异常,隐藏错误是没有意义的,抓住再throw也没意义
        /// 3  除非这个异常对流程没有影响或者你要单独处理这个异常
        /// </summary>
        /// <param name="msg"></param>
        public static void Log(string msg)
        {
            StreamWriter sw = null;
            try
            {
                string fileName = "log.txt";
                string totalPath = Path.Combine(LogPath, fileName);

                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                sw = File.AppendText(totalPath);
                sw.WriteLine(string.Format("{0}:{1}", DateTime.Now, msg));
                sw.WriteLine("***************************************************");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);//log
                //throw ex;
                //throw new exception("这里异常");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
        }

3 三种序列化器

在序列化类之前先用 [Serializable]  //必须添加序列化特性

不序列化的属性使用[NonSerialized] 特性标记

/// <summary>
        /// 二进制序列化器
        /// </summary>
        public static List<Programmer> BinarySerialize(List<Programmer> list)
        {
            //使用二进制序列化对象
            string fileName = Path.Combine("路径地址", @"BinarySerialize.txt");//文件名称与路径
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {//需要一个stream,这里是直接写入文件了
                BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
                binFormat.Serialize(fStream, list);
            }
            //反序列化
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {//需要一个stream,这里是来源于文件
                BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
                //使用二进制反序列化对象
                fStream.Position = 0;//重置流位置
                List<Programmer> pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化对象
                return pList;
            }
        }
 /// <summary>
        /// soap序列化器
        /// </summary>
        public static List<Programmer> SoapSerialize(List<Programmer> list)
        {
            //使用Soap序列化对象
            string fileName = Path.Combine("路径地址", @"SoapSerialize.txt");//文件名称与路径
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
                //soapFormat.Serialize(fStream, list);//SOAP不能序列化泛型对象
                soapFormat.Serialize(fStream, list.ToArray());
            }
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
                //使用二进制反序列化对象
                fStream.Position = 0;//重置流位置
                List<Programmer> pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList();//反序列化对象
                return pList;
            }
        }
/// <summary>
        /// XML序列化器
        /// </summary>
        public static List<Programmer> XmlSerialize(List<Programmer> List)
        {
            //使用XML序列化对象
            string fileName = Path.Combine("路径", @"Student.xml");//文件名称与路径
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
                xmlFormat.Serialize(fStream, List);
            }
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
                //使用XML反序列化对象
                fStream.Position = 0;//重置流位置
                List<Programmer> pList = pList = (List<Programmer>)xmlFormat.Deserialize(fStream);
                return pList;
            }
        }
//BinaryFormatter序列化自定义类的对象时,序列化之后的流中带有空字符,以致于无法反序列化,反序列化时总是报错“在分析完成之前就遇到流结尾”(已经调用了stream.Seek(0, SeekOrigin.Begin);)。
//改用XmlFormatter序列化之后,可见流中没有空字符,从而解决上述问题,但是要求类必须有无参数构造函数,而且各属性必须既能读又能写,即必须同时定义getter和setter,若只定义getter,则反序列化后的得到的各个属性的值都为null。
using Newtonsoft.Json;


public class JsonHelper
    {
        #region Json
        /// <summary>
        /// JavaScriptSerializer
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToString<T>(T obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(obj);
        }

        /// <summary>
        /// JavaScriptSerializer
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T StringToObject<T>(string content)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<T>(content);
        }

        /// <summary>
        /// JsonConvert.SerializeObject
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// JsonConvert.DeserializeObject
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T ToObject<T>(string content)
        {
            return JsonConvert.DeserializeObject<T>(content);
        }

        #endregion Json
    }

 

using System.IO;
/// <summary>
        /// 找出全部的子文件夹
        /// </summary>
        /// <param name="rootPath">根目录</param>
        /// <returns></returns>
        public static List<DirectoryInfo> GetAllDirectory(string rootPath)
        {
            List<DirectoryInfo> directoryList = new List<DirectoryInfo>();

            DirectoryInfo directory = new DirectoryInfo(rootPath);
            
            GetChildDirectory(directoryList, directory);

            return directoryList;
        }


        /// <summary>
        /// 找出某个文件夹的子文件夹,,放入集合
        /// 
        /// 递归:方法自身调用自身
        /// </summary>
        /// <param name="directoryList"></param>
        /// <param name="parentDirectory"></param>
        private static void GetChildDirectory(List<DirectoryInfo> directoryList, DirectoryInfo parentDirectory)
        {
            directoryList.AddRange(parentDirectory.GetDirectories());
            if (parentDirectory.GetDirectories() != null && parentDirectory.GetDirectories().Length > 0)
            {
                foreach (var directory in parentDirectory.GetDirectories())
                {
                    GetChildDirectory(directoryList, directory);
                }
            }
        }

XML 与实体字符串转换

 public static class xHelper
    {
        /// <summary>   
        /// 实体转化为XML   
        /// </summary>   
        public static string ParseToXml<T>(this T model, string fatherNodeName)
        {
            var xmldoc = new XmlDocument();
            var modelNode = xmldoc.CreateElement(fatherNodeName);
            xmldoc.AppendChild(modelNode);

            if (model != null)
            {
                foreach (PropertyInfo property in model.GetType().GetProperties())
                {
                    var attribute = xmldoc.CreateElement(property.Name);
                    if (property.GetValue(model, null) != null)
                        attribute.InnerText = property.GetValue(model, null).ToString();
                    //else
                    //    attribute.InnerText = "[Null]";
                    modelNode.AppendChild(attribute);
                }
            }
            return xmldoc.OuterXml;
        }

        /// <summary>   
        /// XML转换为实体,默认 fatherNodeName="body"
        /// </summary> 
        public static T ParseToModel<T>(this string xml, string fatherNodeName = "body") where T : class ,new()
        {
            T model = new T();
            if (string.IsNullOrEmpty(xml))
                return default(T);
            var xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml);

            var attributes = xmldoc.SelectSingleNode(fatherNodeName).ChildNodes;
            foreach (XmlNode node in attributes)
            {
                foreach (var property in model.GetType().GetProperties().Where(property => node.Name == property.Name))
                {
                    if (!string.IsNullOrEmpty(node.InnerText))
                    {
                        property.SetValue(model,
                                          property.PropertyType == typeof(Guid)
                                              ? new Guid(node.InnerText)
                                              : Convert.ChangeType(node.InnerText, property.PropertyType), null);
                    }
                    else
                        property.SetValue(model, null, null);
                }
            }
            return model;
        }

        /// <summary>
        /// XML转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="headtag"></param>
        /// <returns></returns>
        public static List<T> XmlToObjList<T>(this string xml, string headtag)
            where T : new()
        {

            var list = new List<T>();
            XmlDocument doc = new XmlDocument();
            PropertyInfo[] propinfos = null;
            doc.LoadXml(xml);
            //XmlNodeList nodelist = doc.SelectNodes(headtag);  
            XmlNodeList nodelist = doc.SelectNodes(headtag);
            foreach (XmlNode node in nodelist)
            {
                T entity = new T();
                //初始化propertyinfo  
                if (propinfos == null)
                {
                    Type objtype = entity.GetType();
                    propinfos = objtype.GetProperties();
                }
                //填充entity类的属性  
                foreach (PropertyInfo propinfo in propinfos)
                {
                    //实体类字段首字母变成小写的  
                    string name = propinfo.Name.Substring(0, 1) + propinfo.Name.Substring(1, propinfo.Name.Length - 1);
                    XmlNode cnode = node.SelectSingleNode(name);
                    string v = cnode.InnerText;
                    if (v != null)
                        propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
                }
                list.Add(entity);

            }
            return list;

        }
    }

 

public class XmlHelper
    {
        private static string CurrentXMLPath = ConfigurationManager.AppSettings["CurrentXMLPath"];
        /// <summary>
        /// 通过XmlSerializer序列化实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ToXml<T>(T t) where T : new()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());
            Stream stream = new MemoryStream();
            xmlSerializer.Serialize(stream, t);
            stream.Position = 0;  
            StreamReader reader = new StreamReader( stream );  
            string text = reader.ReadToEnd();  
            return text;

            //string fileName = Path.Combine(CurrentXMLPath, @"Person.xml");//文件名称与路径
            //using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            //{
            //    XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
            //    xmlFormat.Serialize(fStream, t);
            //}
            //string[] lines = File.ReadAllLines(fileName);
            //return string.Join("", lines);
        }

        /// <summary>
        /// 字符串序列化成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T ToObject<T>(string content) where T : new()
        {
            using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
                return (T)xmlFormat.Deserialize(stream);
            }

            //string fileName = Path.Combine(CurrentXMLPath, @"Person.xml");
            //using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            //{
            //    XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
            //    return (T)xmlFormat.Deserialize(fStream);
            //}
        }

        /// <summary>
        /// 文件反序列化成实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T FileToObject<T>(string fileName) where T : new()
        {
            fileName = Path.Combine(CurrentXMLPath, @"Student.xml");
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
                return (T)xmlFormat.Deserialize(fStream);
            }
        }

        /*   linq to xml
                public static IEnumerable<Hero<T>> GetHeroEntity(string fileName)
                {
                    XDocument xdoc = XDocument.Load(fileName);
                    XElement root = xdoc.Root;
                    foreach (XElement element in root.Elements())
                    {
                        Hero<T> entity = new Hero<T>();
                        entity.Name = element.Element("Name").Value;
                        foreach (XElement item in element.Element("StoryCollection").Elements())
                        {
                            var story = ReflectionUtils<T>.ElementToEntity(item);
                            entity.list.Add(story);
                        }
                        yield return entity;
                    }
                }

                /// <summary>
                /// 将XElement转换为T类型的实体类
                /// </summary>
                /// <param name="xe">XElement</param>
                /// <returns>T类型的实体类</returns>
                public static T ElementToEntity<T>(XElement xe)
                {
                    T entity = Activator.CreateInstance<T>(); //T entity = new T();
                    Type type = typeof(T);
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo p in properties)
                    {
                        string propertyName = p.Name;
                        Type propertyType = p.PropertyType;
                        object obj = xe.Element(propertyName).Value;
                        object value = http://www.mamicode.com/Convert.ChangeType(obj, propertyType);>*/
    }

 

IOSerialize,xml和json,soap序列化器,二进制序列化器,XML序列化器,文件 检查、新增、复制、移动、删除