using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSerialize.IO { public class ImageHelper { private static string ImagePath = System.Configuration.ConfigurationManager.AppSettings["ImagePath"]; private static string VerifyPath = System.Configuration.ConfigurationManager.AppSettings["ImagePath"]; //绘图的原理很简单:Bitmap就像一张画布,Graphics如同画图的手,把Pen或Brush等绘图对象画在Bitmap这张画布上 /// <summary> /// 画验证码 /// </summary> public static void Drawing() { Bitmap bitmapobj = new Bitmap(100, 100); //在Bitmap上创建一个新的Graphics对象 Graphics g = Graphics.FromImage(bitmapobj); //创建绘画对象,如Pen,Brush等 Pen redPen = new Pen(Color.Red, 8); g.Clear(Color.White); //绘制图形 g.DrawLine(redPen, 50, 20, 500, 20); g.DrawEllipse(Pens.Black, new Rectangle(0, 0, 200, 100));//画椭圆 g.DrawArc(Pens.Black, new Rectangle(0, 0, 100, 100), 60, 180);//画弧线 g.DrawLine(Pens.Black, 10, 10, 100, 100);//画直线 g.DrawRectangle(Pens.Black, new Rectangle(0, 0, 100, 200));//画矩形 g.DrawString("我爱北京天安门", new Font("微软雅黑", 12), new SolidBrush(Color.Red), new PointF(10, 10));//画字符串 //g.DrawImage( if (!Directory.Exists(ImagePath)) Directory.CreateDirectory(ImagePath); bitmapobj.Save(ImagePath + "pic1.jpg", ImageFormat.Jpeg); //释放所有对象 bitmapobj.Dispose(); g.Dispose(); } public static void VerificationCode() { Bitmap bitmapobj = new Bitmap(300, 300); //在Bitmap上创建一个新的Graphics对象 Graphics g = Graphics.FromImage(bitmapobj); g.DrawRectangle(Pens.Black, new Rectangle(0, 0, 150, 50));//画矩形 g.FillRectangle(Brushes.White, new Rectangle(1, 1, 149, 49)); g.DrawArc(Pens.Blue, new Rectangle(10, 10, 140, 10), 150, 90);//干扰线 string[] arrStr = new string[] { "我", "们", "孝", "行", "白", "到", "国", "中", "来", "真" }; Random r = new Random(); int i; for (int j = 0; j < 4; j++) { i = r.Next(10); g.DrawString(arrStr[i], new Font("微软雅黑", 15), Brushes.Red, new PointF(j * 30, 10)); } bitmapobj.Save(Path.Combine(VerifyPath, "Verif.jpg"), ImageFormat.Jpeg); bitmapobj.Dispose(); g.Dispose(); } /// <summary> /// 按比例缩放,图片不会变形,会优先满足原图和最大长宽比例最高的一项 /// </summary> /// <param name="oldPath"></param> /// <param name="newPath"></param> /// <param name="maxWidth"></param> /// <param name="maxHeight"></param> public static void CompressPercent(string oldPath, string newPath, int maxWidth, int maxHeight) { System.Drawing.Image _sourceImg = System.Drawing.Image.FromFile(oldPath); double _newW = (double)maxWidth; double _newH = (double)maxHeight; double percentWidth = (double)_sourceImg.Width > maxWidth ? (double)maxWidth : (double)_sourceImg.Width; if ((double)_sourceImg.Height * (double)percentWidth / (double)_sourceImg.Width > (double)maxHeight) { _newH = (double)maxHeight; _newW = (double)maxHeight / (double)_sourceImg.Height * (double)_sourceImg.Width; } else { _newW = percentWidth; _newH = (percentWidth / (double)_sourceImg.Width) * (double)_sourceImg.Height; } System.Drawing.Image bitmap = new System.Drawing.Bitmap((int)_newW, (int)_newH); Graphics g = Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage(_sourceImg, new Rectangle(0, 0, (int)_newW, (int)_newH), new Rectangle(0, 0, _sourceImg.Width, _sourceImg.Height), GraphicsUnit.Pixel); _sourceImg.Dispose(); g.Dispose(); bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } /// <summary> /// 按照指定大小对图片进行缩放,可能会图片变形 /// </summary> /// <param name="oldPath"></param> /// <param name="newPath"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> public static void ImageChangeBySize(string oldPath, string newPath, int newWidth, int newHeight) { Image sourceImg = Image.FromFile(oldPath); System.Drawing.Image bitmap = new System.Drawing.Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage(sourceImg, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, sourceImg.Width, sourceImg.Height), GraphicsUnit.Pixel); sourceImg.Dispose(); g.Dispose(); bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSerialize.IO { /// <summary> /// 文件夹 文件管理 /// </summary> public class MyIO { /// <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; /// <summary> /// 读取文件夹 文件信息 /// </summary> public static void Show() { {//check if (!Directory.Exists(LogPath))//检测文件夹是否存在 { } DirectoryInfo directory = new DirectoryInfo(LogPath);//不存在不报错 注意exists属性 Console.WriteLine(string.Format("{0} {1} {2}", directory.FullName, directory.CreationTime, directory.LastWriteTime)); if (!File.Exists(Path.Combine(LogPath, "info.txt"))) { } FileInfo fileInfo = new FileInfo(Path.Combine(LogPath, "info.txt")); Console.WriteLine(string.Format("{0} {1} {2}", fileInfo.FullName, fileInfo.CreationTime, fileInfo.LastWriteTime)); } {//Directory if (!Directory.Exists(LogPath)) { DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);//一次性创建全部的子路径 Directory.Move(LogPath, LogMovePath);//移动 原文件夹就不在了 Directory.Delete(LogMovePath);//删除 } } {//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> /// 关于异常处理:(链接:http://pan.baidu.com/s/1kVNorpd 密码:pyhv) /// 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(); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSerialize.IO { public class Recursion { /// <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); //directoryList.Add(directory); //directoryList.AddRange(directory.GetDirectories()); //foreach (var child in directory.GetDirectories()) //{ // directoryList.AddRange(child.GetDirectories()); // foreach (var grand in child.GetDirectories()) // { // } //} 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); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using Newtonsoft.Json; namespace IOSerialize.Serialize { 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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSerialize.Serialize { [Serializable] //必须添加序列化特性 public class Person { [NonSerialized] public int Id = 1; public string Name { get; set; } public string Sex { get; set; } } [Serializable] //必须添加序列化特性 public class Programmer : Person { private string Language { get; set; }//编程语言 public string Description { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace IOSerialize.Serialize { public class SerializeHelper { private static string CurrentDataPath = ConfigurationManager.AppSettings["CurrentDataPath"]; /// <summary> /// 二进制序列化器 /// </summary> public static void BinarySerialize() { //使用二进制序列化对象 string fileName = Path.Combine(CurrentDataPath, @"BinarySerialize.txt");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) {//需要一个stream,这里是直接写入文件了 List<Programmer> pList = DataFactory.BuildProgrammerList(); BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器 binFormat.Serialize(fStream, pList); } 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);//反序列化对象 } } /// <summary> /// soap序列化器 /// </summary> public static void SoapSerialize() { //使用Soap序列化对象 string fileName = Path.Combine(CurrentDataPath, @"SoapSerialize.txt");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { List<Programmer> pList = DataFactory.BuildProgrammerList(); SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器 //soapFormat.Serialize(fStream, list);//SOAP不能序列化泛型对象 soapFormat.Serialize(fStream, pList.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();//反序列化对象 } } //BinaryFormatter序列化自定义类的对象时,序列化之后的流中带有空字符,以致于无法反序列化,反序列化时总是报错“在分析完成之前就遇到流结尾”(已经调用了stream.Seek(0, SeekOrigin.Begin);)。 //改用XmlFormatter序列化之后,可见流中没有空字符,从而解决上述问题,但是要求类必须有无参数构造函数,而且各属性必须既能读又能写,即必须同时定义getter和setter,若只定义getter,则反序列化后的得到的各个属性的值都为null。 /// <summary> /// XML序列化器 /// </summary> public static void XmlSerialize() { //使用XML序列化对象 string fileName = Path.Combine(CurrentDataPath, @"Student.xml");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { List<Programmer> pList = DataFactory.BuildProgrammerList(); XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型 xmlFormat.Serialize(fStream, pList); } 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); } } public static void Json() { List<Programmer> pList = DataFactory.BuildProgrammerList(); string result = JsonHelper.ObjectToString<List<Programmer>>(pList); List<Programmer> pList1 = JsonHelper.StringToObject<List<Programmer>>(result); } } }
using System; using System.Linq; using System.Xml; using System.Reflection; using System.Data; using System.Collections.Generic; namespace IOSerialize.Serialize { 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; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Xml.Serialization; namespace IOSerialize.Serialize { 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 = Convert.ChangeType(obj, propertyType); p.SetValue(entity, value); } return entity; } */ } }
using IOSerialize.Serialize; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSerialize { public class DataFactory { /// <summary> /// 妹子太稀少了。。 /// </summary> /// <returns></returns> public static List<Programmer> BuildProgrammerList() { #region data prepare List<Programmer> list = new List<Programmer>(); list.Add(new Programmer() { Id = 1, Description="高级班学员", Name = "SoWhat", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "day", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "领悟", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "Sam", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "AlphaGo", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "折腾", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "Me860", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "打兔子的猎人", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "Nine", Sex = "女" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "望", Sex = "女" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "微笑刺客", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "waltz", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "爱在昨天", Sex = "男" }); list.Add(new Programmer() { Id = 1, Description = "高级班学员", Name = "waltz", Sex = "男" }); #endregion return list; } } }
using IOSerialize.IO; using IOSerialize.Serialize; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading.Tasks; namespace IOSerialize { /// <summary> /// 1 文件夹/文件 检查、新增、复制、移动、删除, /// 2 文件读写,记录文本日志/读取配置文件 /// 3 try catch的正确姿势(链接:http://pan.baidu.com/s/1kVNorpd 密码:pyhv) /// 4 递归的编程技巧 /// 5 三种序列化器 /// 6 xml和json /// 7 验证码、图片缩放 /// 8 作业部署 /// </summary> class Program { static void Main(string[] args) { try { Console.WriteLine("欢迎来到.Net高级班vip课程,今天是Eleven老师为大家带来的IO和序列化"); //MyIO.Show(); //List<DirectoryInfo> dicList = Recursion.GetAllDirectory(@"D:\ruanmou\online8\homework\1"); SerializeHelper.BinarySerialize(); SerializeHelper.SoapSerialize(); SerializeHelper.XmlSerialize(); List<Programmer> list = DataFactory.BuildProgrammerList(); { string xmlResult = XmlHelper.ToXml<List<Programmer>>(list); List<Programmer> list1 = XmlHelper.ToObject<List<Programmer>>(xmlResult); List<Programmer> list2 = XmlHelper.FileToObject<List<Programmer>>(""); } SerializeHelper.Json(); { string jResult = JsonHelper.ObjectToString<List<Programmer>>(list); List<Programmer> list1 = JsonHelper.StringToObject<List<Programmer>>(jResult); } { string jResult = JsonHelper.ToJson<List<Programmer>>(list); List<Programmer> list1 = JsonHelper.ToObject<List<Programmer>>(jResult); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); } } }