查看链接 https://github.com/jungle8884/C-.Net/tree/MyClassLibrary
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Jungle8884 8 { 9 /// <summary> 10 /// 对应于SerializeHelper,必须添加可序列化特性 11 /// </summary> 12 [Serializable] 13 public class Person 14 { 15 [NonSerialized] 16 public int Id = 1; 17 18 public string Name { get; set; } 19 20 public string Gender { get; set; } 21 22 } 23 24 [Serializable] 25 public class Programmer : Person 26 { 27 private string Language { get; set; } 28 29 public string Description { get; set; } 30 31 } 32 33 /// <summary> 34 /// 数据工厂 35 /// </summary> 36 public class DataFactory 37 { 38 /// <summary> 39 /// 初始化数据---用于测试 40 /// </summary> 41 /// <returns></returns> 42 public static List<Programmer> BuildProgrammerList() 43 { 44 #region data-prepare 45 List<Programmer> list = new List<Programmer>(); 46 list.Add(new Programmer() 47 { 48 Id = 1, 49 Description = "高级班学员", 50 Name = "SoWhat", 51 Gender = "男" 52 }); 53 list.Add(new Programmer() 54 { 55 Id = 1, 56 Description = "高级班学员", 57 Name = "day", 58 Gender = "男" 59 }); 60 list.Add(new Programmer() 61 { 62 Id = 1, 63 Description = "高级班学员", 64 Name = "领悟", 65 Gender = "男" 66 }); 67 list.Add(new Programmer() 68 { 69 Id = 1, 70 Description = "高级班学员", 71 Name = "Sam", 72 Gender = "男" 73 }); 74 list.Add(new Programmer() 75 { 76 Id = 1, 77 Description = "高级班学员", 78 Name = "AlphaGo", 79 Gender = "男" 80 }); 81 list.Add(new Programmer() 82 { 83 Id = 1, 84 Description = "高级班学员", 85 Name = "折腾", 86 Gender = "男" 87 }); 88 list.Add(new Programmer() 89 { 90 Id = 1, 91 Description = "高级班学员", 92 Name = "Me860", 93 Gender = "男" 94 }); 95 list.Add(new Programmer() 96 { 97 Id = 1, 98 Description = "高级班学员", 99 Name = "打兔子的猎人", 100 Gender = "男" 101 }); 102 list.Add(new Programmer() 103 { 104 Id = 1, 105 Description = "高级班学员", 106 Name = "Nine", 107 Gender = "女" 108 }); 109 list.Add(new Programmer() 110 { 111 Id = 1, 112 Description = "高级班学员", 113 Name = "望", 114 Gender = "女" 115 }); 116 list.Add(new Programmer() 117 { 118 Id = 1, 119 Description = "高级班学员", 120 Name = "微笑刺客", 121 Gender = "男" 122 }); 123 list.Add(new Programmer() 124 { 125 Id = 1, 126 Description = "高级班学员", 127 Name = "waltz", 128 Gender = "男" 129 }); 130 list.Add(new Programmer() 131 { 132 Id = 1, 133 Description = "高级班学员", 134 Name = "爱在昨天", 135 Gender = "男" 136 }); 137 list.Add(new Programmer() 138 { 139 Id = 1, 140 Description = "高级班学员", 141 Name = "waltz", 142 Gender = "男" 143 }); 144 #endregion 145 146 return list; 147 } 148 } 149 }
IO: 97和69两行可以模拟控制台自动输出---模拟黑客。。。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Configuration; 5 using System.IO; 6 using System.Threading; 7 8 namespace Jungle 9 { 10 public class MyIO 11 { 12 //日志文件名 13 private static string sLogFileName = Path.Combine(MyConstants.LogPathAbsolute, "Log.txt"); 14 /// <summary> 15 /// 写日志 16 /// </summary> 17 /// <param name="sWriteIn"></param> 18 public static void WriteLogsWriteLine(string sWriteIn) 19 { 20 if (!File.Exists(sLogFileName)) 21 { 22 //1 先创建文件夹 23 Directory.CreateDirectory(MyConstants.LogPathAbsolute); 24 //2 再创建文件 25 using (FileStream fileStream = File.Create(sLogFileName))//打开文件流 (创建文件并写入) 26 { 27 StreamWriter sw = new StreamWriter(fileStream); 28 sw.WriteLine(sWriteIn); 29 sw.Flush(); 30 #region 其他方法---字节流 31 //byte[] bytes = Encoding.Default.GetBytes(sWriteIn); 32 //fileStream.Write(bytes, 0, bytes.Length); 33 //fileStream.Flush(); 34 #endregion 35 } 36 } 37 } 38 /// <summary> 39 /// 写日志---追加 40 /// </summary> 41 public static void WriteLogsAppendText(string sWriteIn) 42 { 43 using (StreamWriter sw = File.AppendText(sLogFileName)) 44 { 45 sw.WriteLine(sWriteIn); 46 sw.Flush(); 47 } 48 49 } 50 51 /// <summary> 52 /// 读取日志输出到控制台 53 /// 适合小数据文件 54 /// </summary> 55 public static void ReadLogsToConsole() 56 { 57 foreach (string sResult in File.ReadAllLines(sLogFileName)) 58 { 59 #region 其他方法---仅供参考 60 //string sResult = File.ReadAllText(sLogFileName);//一次性读取所有的文本 61 62 //Byte[] byteContent = File.ReadAllBytes(sLogFileName);//字节流的方式读取 63 //string sResultByte = Encoding.UTF8.GetString(byteContent);//字节流解码为字符串 64 #endregion 65 char[] cResult = sResult.ToCharArray(); 66 foreach (char c in cResult) 67 { 68 Console.Write(c); 69 Thread.Sleep(200); 70 } 71 Console.WriteLine(); 72 } 73 } 74 75 /// <summary> 76 /// 读取大文件使用(当然小文件一样适用) 77 /// 采用策略:分批读取 78 /// </summary> 79 public static void ReadLargeFileToConsole() 80 { 81 using (FileStream stream = File.OpenRead(sLogFileName)) 82 { 83 int iLength = 10;//指定每次读取长度 84 int iResult = 0; 85 86 do 87 { 88 byte[] bytes = new byte[iLength]; 89 iResult = stream.Read(bytes,0,iLength);//返回读取的字节数 90 Console.Write((Encoding.UTF8.GetString(bytes, 0, iResult)));//直接输出一句 91 #region 按字节输出 92 //for (int i = 0; i < iResult; i++) 93 //{ 94 // Console.Write((bytes[i].ToString())); 95 //} 96 #endregion 97 Thread.Sleep(300); 98 } 99 while (iLength == iResult); 100 } 101 } 102 103 /// <summary> 104 /// 通过递归获取根目录下的所有子文件夹 105 /// 适用于无限集 106 /// 缺点:耗内存 107 /// </summary> 108 /// <param name="directoryList">存放所有文件夹的集合</param> 109 /// <param name="directoryParent">根目录文件夹</param> 110 public static void GetChildDirectoryByRecursion(List<DirectoryInfo> directoryList, DirectoryInfo directoryParent) 111 { 112 DirectoryInfo[] directoryListChild = directoryParent.GetDirectories(); 113 directoryList.AddRange(directoryListChild); 114 if (directoryListChild.Length > 0)//跳出条件--->出口 115 { 116 foreach (var directoryChild in directoryListChild) 117 { 118 GetChildDirectoryByRecursion(directoryList, directoryChild);//相同的代码抽取出来--->递归 119 } 120 } 121 } 122 } 123 }
配置路径的新思想:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Configuration; 7 8 namespace Jungle 9 { 10 public class MyConstants 11 { 12 /// <summary> 13 /// 配置绝对路径---模板 14 /// </summary> 15 public static string LogPathAbsolute = ConfigurationManager.AppSettings["LogPath"]; 16 17 /// <summary> 18 /// 配置相对路径---获取当前程序路径 19 /// </summary> 20 public static string LogPathRelative = AppDomain.CurrentDomain.BaseDirectory; 21 22 /// <summary> 23 /// 序列化数据地址 24 /// </summary> 25 public static string BinarySerializeDataPath = ConfigurationManager.AppSettings["BinarySerializeDataPath"]; //二进制 26 public static string SoapSerializeDataPath = ConfigurationManager.AppSettings["SoapSerializeDataPath"]; //Soap 27 public static string XmlSerializeDataPath = ConfigurationManager.AppSettings["XmlSerializeDataPath"]; //Soap 28 } 29 }
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <startup> 4 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> 5 </startup> 6 <appSettings><!-- 每台电脑的路径不一样,可自己更改 --> 7 <add key="LogPath" value="D:CodingProjectJungle8884FilesLogs"/> 8 <add key="BinarySerializeDataPath" value="D:CodingProjectJungle8884FilesSerialize"/> 9 <add key="SoapSerializeDataPath" value="D:CodingProjectJungle8884FilesSoap"/> 10 <add key="XmlSerializeDataPath" value="D:CodingProjectJungle8884FilesXml"/> 11 </appSettings> 12 </configuration>
Serialize:
1 using Jungle8884; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Runtime.Serialization.Formatters.Binary; 7 using System.Runtime.Serialization.Formatters.Soap; 8 using System.Text; 9 using System.Threading.Tasks; 10 using System.Xml.Serialization; 11 12 namespace Jungle 13 { 14 /// <summary> 15 /// 本序列化只作为一个例子 16 /// 对应于Programmer类 17 /// 具体情况可以更改为泛型或具体类型 18 /// </summary> 19 public class MySerializableHelper 20 { 21 /// <summary> 22 /// 存放文件名称与路径 23 /// </summary> 24 private static string sFileNameBinary = Path.Combine(MyConstants.BinarySerializeDataPath, "BinarySerialize.txt"); 25 private static string sFileNameSoap = Path.Combine(MyConstants.SoapSerializeDataPath, "SoapSerialize.txt"); 26 private static string sFileNameXml = Path.Combine(MyConstants.XmlSerializeDataPath, "Programmer.xml"); 27 28 #region 二进制序列化 29 30 public static void BinarySerialize(List<Programmer> pList) 31 { 32 using (Stream fStream = new FileStream(sFileNameBinary, FileMode.Create, FileAccess.ReadWrite)) 33 { 34 pList = DataFactory.BuildProgrammerList(); 35 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器 36 binFormat.Serialize(fStream, pList); 37 } 38 } 39 40 public static List<Programmer> BinaryDeserialize() 41 { 42 List<Programmer> pList = null; 43 using (Stream fStream = new FileStream(sFileNameBinary, FileMode.Open, FileAccess.ReadWrite)) 44 { 45 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器 46 fStream.Position = 0; 47 pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化 48 } 49 return pList; 50 } 51 52 #endregion 53 54 #region Soap序列化 55 56 public static void SoapSerialize(List<Programmer> pList) 57 { 58 using (Stream fStream = new FileStream(sFileNameSoap, FileMode.Create, FileAccess.ReadWrite)) 59 { 60 pList = DataFactory.BuildProgrammerList(); 61 SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器 62 //soapFormat.Serialize(fStream, pList);//SOAP不能序列化泛型对象 63 soapFormat.Serialize(fStream, pList.ToArray()); 64 } 65 } 66 67 public static List<Programmer> SoapDeserialize() 68 { 69 List<Programmer> pList = null; 70 using (Stream fStream = new FileStream(sFileNameSoap, FileMode.Open, FileAccess.ReadWrite)) 71 { 72 SoapFormatter soapFormat = new SoapFormatter(); 73 fStream.Position = 0; 74 pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList(); 75 } 76 return pList; 77 } 78 79 #endregion 80 81 //BinaryFormatter序列化自定义类的对象时,序列化之后的流中带有空字符,以致于无法反序列化, 82 //反序列化时总是报错“在分析完成之前就遇到流结尾”(已经调用了stream.Seek(0, SeekOrigin.Begin);)。 83 //改用XmlFormatter序列化之后,可见流中没有空字符,从而解决上述问题,但是要求类必须有无参数构造函数, 84 //而且各属性必须既能读又能写,即必须同时定义getter和setter,若只定义getter,则反序列化后的得到的各个属性的值都为null。 85 86 #region Xml序列化 87 88 public static void XmlSerialize(List<Programmer> pList) 89 { 90 using (Stream fStream = new FileStream(sFileNameXml, FileMode.Create, FileAccess.ReadWrite)) 91 { 92 pList = DataFactory.BuildProgrammerList(); 93 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>)); 94 xmlFormat.Serialize(fStream, pList); 95 } 96 } 97 98 public static List<Programmer> XmlDeserialize() 99 { 100 List<Programmer> pList = null; 101 using (Stream fStream = new FileStream(sFileNameXml, FileMode.Open, FileAccess.ReadWrite)) 102 { 103 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>)); 104 fStream.Position = 0; 105 pList = (List<Programmer>)xmlFormat.Deserialize(fStream); 106 } 107 return pList; 108 } 109 110 #endregion 111 112 #region Json序列化分为两种:微软的和Newtonsoft的 113 114 //对象到Json字符串叫序列化 115 public static string JsonSerialize(List<Programmer> pList) 116 { 117 pList = DataFactory.BuildProgrammerList(); 118 string sResultJson = MyJsonHelper.ObjectToString<List<Programmer>>(pList); 119 return sResultJson; 120 } 121 public static string JsonSerializeNewtonsoft(List<Programmer> pList) 122 { 123 pList = DataFactory.BuildProgrammerList(); 124 string sResultJson = MyJsonHelper.ToJson<List<Programmer>>(pList); 125 return sResultJson; 126 } 127 128 //Json字符串到对象叫反序列化 129 public static List<Programmer> JsonDeserialize(string sJson) 130 { 131 List<Programmer> pList = MyJsonHelper.StringToObject<List<Programmer>>(sJson); 132 return pList; 133 } 134 public static List<Programmer> JsonDeserializeNewtonsoft(string sJson) 135 { 136 List<Programmer> pList = MyJsonHelper.ToObject<List<Programmer>>(sJson); 137 return pList; 138 } 139 #endregion 140 141 } 142 }
1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Web.Script.Serialization;//System.Web.Extensions 8 9 namespace Jungle 10 { 11 public class MyJsonHelper 12 { 13 14 #region 微软自带Json序列化 15 /// <summary> 16 /// (Object到)Json的序列化 17 /// </summary> 18 /// <typeparam name="T">对象类型</typeparam> 19 /// <param name="obj">对象实例</param> 20 /// <returns>返回字符串</returns> 21 public static string ObjectToString<T>(T obj) 22 { 23 JavaScriptSerializer jss = new JavaScriptSerializer(); 24 return jss.Serialize(obj); 25 } 26 /// <summary> 27 /// Json(到Object)的反序列化 28 /// </summary> 29 /// <typeparam name="T">反序列化到对象类型</typeparam> 30 /// <param name="sContent">待反序列化的字符串</param> 31 /// <returns></returns> 32 public static T StringToObject<T>(string sContent) 33 { 34 JavaScriptSerializer jss = new JavaScriptSerializer(); 35 return jss.Deserialize<T>(sContent); 36 } 37 #endregion 38 39 #region Newtonsoft.Json 40 /// <summary> 41 /// (Object到)Json 42 /// </summary> 43 /// <typeparam name="T"></typeparam> 44 /// <param name="obj"></param> 45 /// <returns></returns> 46 public static string ToJson<T>(T obj) 47 { 48 return JsonConvert.SerializeObject(obj); 49 } 50 51 /// <summary> 52 /// (Json到)Object 53 /// </summary> 54 /// <typeparam name="T"></typeparam> 55 /// <param name="sContent"></param> 56 /// <returns></returns> 57 public static T ToObject<T>(string sContent) 58 { 59 return JsonConvert.DeserializeObject<T>(sContent); 60 } 61 #endregion 62 63 } 64 }
测试代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Diagnostics; 4 using System.IO; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 using Jungle; 9 10 namespace Jungle8884 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 MySafeInvoke.InvokeMethod(() => { 17 //MyIO.WriteLogsWriteLine("Get up to cheer up!"); 18 //MyIO.WriteLogsAppendText("睡你麻痹,起来嗨!"); 19 //MyIO.WriteLogsAppendText("为什么?"); 20 //MyIO.WriteLogsAppendText("你很帅啊!"); 21 //MyIO.WriteLogsAppendText("真的!"); 22 //MyIO.WriteLogsAppendText("我不信..."); 23 //MyIO.WriteLogsAppendText("这是真的!"); 24 //MyIO.WriteLogsAppendText("这不是梦!"); 25 //MyIO.ReadLogsToConsole(); 26 //MyIO.ReadLargeFileToConsole(); 27 //Process.Start(Path.Combine(MyConstants.LogPathAbsolute, "Log.txt"));//打开文本文件 28 List<Programmer> pList = null; 29 MySerializableHelper.BinarySerialize(pList); 30 MySerializableHelper.SoapSerialize(pList); 31 MySerializableHelper.XmlSerialize(pList); 32 }); 33 } 34 } 35 }
下载链接:
链接:https://pan.baidu.com/s/1mjNnqQ0 密码:pco3