1 文件夾/文件 檢查、新增、複製、移動、刪除,2 文件讀寫,記錄文本日誌/讀取配置文件3 三種序列化器4 xml和json1.文件夾/文件 檢查、新增、複製、移動、刪除,2 文件讀寫,記錄文本日誌/讀取配置文件 日誌方法 3 三種序列化器 在序列化類之前先用 [Serializable] //必須 ...
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 = Convert.ChangeType(obj, propertyType); p.SetValue(entity, value); } return entity; } */ }