首页 > 代码库 > IO&Seralize

IO&Seralize

IO

技术分享
 1 <appSettings>
 2     <!--日志路径-->
 3     <add key="LogPath" value=http://www.mamicode.com/"E:\学习\C#进阶\fsociety\fSociety0\Logs\Log\"/>
 4     <add key="LogMovePath" value=http://www.mamicode.com/"E:\学习\C#进阶\fsociety\fSociety0\Logs\LogMove\"/>
 5     <!--<add key="LogPath" value=http://www.mamicode.com/"D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Log\"/>
 6     <add key="LogMovePath" value=http://www.mamicode.com/"D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\LogMove\"/>
 7     <add key="ImagePath" value=http://www.mamicode.com/"D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Image\"/>-->
 8     <add key="VerifyPath" value=http://www.mamicode.com/"D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Image\"/>
 9     <add key="CurrentDataPath" value=http://www.mamicode.com/"D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\File\"/>
10   </appSettings>
appSettings
1         /// <summary>
2         /// 配置绝对路径
3         /// </summary>
4         private static string LogPath = ConfigurationManager.AppSettings["LogPath"];
5         private static string LogMovePath = ConfigurationManager.AppSettings["LogMovePath"];
6         /// <summary>
7         /// 获取当前程序路径
8         /// </summary>
9         private static string LogPath2 = AppDomain.CurrentDomain.BaseDirectory;       
Directory
1        {//Directory
2                 bool isExists = Directory.Exists(LogPath);
3                 if (!isExists)
4                 {
5                     DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);//一次性创建全部的子路径
6                     Directory.Move(LogPath, LogMovePath);//移动  原文件夹就不在了
7                     Directory.Delete(LogMovePath);//删除
8                 }
9             }

 

File

 1         {//File
 2                 string fileName = Path.Combine(LogPath, "log.txt");
 3                 string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
 4                 string fileNameMove = Path.Combine(LogPath, "logMove.txt");
 5                 bool isExists = File.Exists(fileName);
 6                 if (!isExists)
 7                 {
 8                     Directory.CreateDirectory(LogPath);
 9                     using (FileStream stream = File.Create(fileName))//创建文件并写入
10                     {
11                         string name = "12345567778890";
12 
13                         byte[] bytes = Encoding.Default.GetBytes(name);
14                         stream.Write(bytes, 0, bytes.Length);
15                         stream.Flush();
16                     }
17 
18                     string msg = "今天是Course6IOSerialize,今天上课的人有26个人";
19                     using (StreamWriter sw = File.AppendText(fileName))
20                     {
21                         sw.WriteLine(msg);
22                         sw.Flush();
23                     }
24 
25                     foreach (string result in File.ReadAllLines(fileName))
26                     {
27                         Console.WriteLine(result);
28                     }
29                     File.ReadAllText(fileName);
30                     File.ReadAllBytes(fileName);
31 
32                     using (FileStream stream = File.OpenRead(fileName))//分批读取
33                     {
34                         int length = 5;
35                         int result = 0;
36 
37                         do
38                         {
39                             byte[] bytes = new byte[length];
40                             result = stream.Read(bytes, 0, 5);
41                             for (int i = 0; i < result; i++)
42                             {
43                                 Console.WriteLine(bytes[i].ToString());
44                             }
45                         }
46                         while (length == result);
47                     }
48 
49                     File.Copy(fileName, fileNameCopy);
50                     File.Move(fileName, fileNameMove);
51                     File.Delete(fileNameCopy);
52                     File.Delete(fileNameMove);
53 
54                 }
55             }

 

Log

技术分享
 1         public static void Log(string msg)
 2         {
 3             StreamWriter sw = null;
 4             try
 5             {
 6                 string fileName = "log.txt";
 7                 string totalPath = Path.Combine(LogPath, fileName);
 8                 //int i = 0;
 9 
10                 //int result = 5 / i;
11 
12                 if (Directory.Exists(LogPath))
13                 {
14                     if (File.Exists(totalPath))
15                         sw = File.AppendText(totalPath);
16                     else
17                         sw = File.CreateText(totalPath);
18                 }
19                 else
20                 {
21                     Directory.CreateDirectory(LogPath);
22                     sw = File.CreateText(totalPath);
23                 }
24                 sw.WriteLine(string.Format("{0}:{1}", DateTime.Now, msg));
25                 sw.WriteLine("***************************************************");
26             }
27             catch (Exception ex)
28             {
29                 Console.WriteLine(ex.Message);//log
30                 //throw ex;
31                 //throw new exception("这里异常");
32             }
33             finally
34             {
35                 if (sw != null)
36                 {
37                     sw.Flush();
38                     sw.Close();
39                     sw.Dispose();
40                 }
41             }
42         }    
Log
技术分享
 1     public class Recursion
 2     {
 3         public static List<DirectoryInfo> FindAll(string rootPath)
 4         {
 5             List<DirectoryInfo> dirList = new List<DirectoryInfo>();
 6             DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);//1
 7             dirList.Add(rootDirectory);
 8             FindChild(rootDirectory, dirList);
 9 
10             return dirList;
11         }
12 
13         /// <summary>
14         /// 找出文件夹的子文件夹,放入集合,
15         /// 遍历子文件,再。。。。
16         /// </summary>
17         /// <param name="parentDirectory">文件夹</param>
18         /// <param name="dirList">集合</param>
19         private static void FindChild(DirectoryInfo parentDirectory, List<DirectoryInfo> dirList)
20         {
21             DirectoryInfo[] dirChildList = parentDirectory.GetDirectories();
22             dirList.AddRange(dirChildList);
23             if (dirChildList != null && dirChildList.Length > 0)//1 递归一定要有跳出条件
24             {
25                 foreach (var child in dirChildList)//2 递归很耗资源
26                 {
27                     FindChild(child, dirList);
28                 }
29             }
30         }
31     }
Recursion
技术分享
 1         private static List<Programmer> GetProgrammerList()
 2         {
 3             List<Programmer> list = new List<Programmer>();
 4             list.Add(new Programmer()
 5             {
 6                 Name = "快乐阳光",
 7                 Sex = ""
 8             });
 9             list.Add(new Programmer()
10             {
11                 Name = "荼蘼",
12                 Sex = ""
13             });
14             list.Add(new Programmer()
15             {
16                 Name = "笑对人生",
17                 Sex = ""
18             });
19             list.Add(new Programmer()
20             {
21                 Name = "yizi",
22                 Sex = ""
23             });
24             list.Add(new Programmer()
25             {
26                 Name = "萌萌的",
27                 Sex = ""
28             });
29             list.Add(new Programmer()
30             {
31                 Name = "红领巾",
32                 Sex = ""
33             });
34             list.Add(new Programmer()
35             {
36                 Name = "net",
37                 Sex = ""
38             });
39             return list;
40         }
List

Serialize

技术分享
 1         /// <summary>
 2         /// JavaScriptSerializer
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <returns></returns>
 7         public static string ObjectToString<T>(T obj)
 8         {
 9             JavaScriptSerializer jss = new JavaScriptSerializer();
10             return jss.Serialize(obj);
11         }
12 
13         /// <summary>
14         /// JavaScriptSerializer
15         /// </summary>
16         /// <typeparam name="T"></typeparam>
17         /// <param name="content"></param>
18         /// <returns></returns>
19         public static T StringToObject<T>(string content)
20         {
21             JavaScriptSerializer jss = new JavaScriptSerializer();
22             return jss.Deserialize<T>(content);
23         }
24 
25         /// <summary>
26         /// JsonConvert.SerializeObject
27         /// </summary>
28         /// <typeparam name="T"></typeparam>
29         /// <param name="obj"></param>
30         /// <returns></returns>
31         public static string ToJson<T>(T obj)
32         {
33             return JsonConvert.SerializeObject(obj);
34         }
35 
36         /// <summary>
37         /// JsonConvert.DeserializeObject
38         /// </summary>
39         /// <typeparam name="T"></typeparam>
40         /// <param name="content"></param>
41         /// <returns></returns>
42         public static T ToObject<T>(string content)
43         {
44             return JsonConvert.DeserializeObject<T>(content);
45         }        
JavaScriptSerializer
技术分享
 1        public static string ToXml<T>(T t) where T : new()
 2         {
 3             string fileName = @"E:\online_3\20150806第三期高级班Course10SerializeJson\Course10SerializeJson\Course10SerializeJson\file\Person.xml";//文件名称与路径
 4             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 5             {
 6                 XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
 7                 xmlFormat.Serialize(fStream, t);
 8             }
 9             string[] lines = File.ReadAllLines(fileName);
10             return string.Join("", lines);
11         }
12 
13         public static T ToObject<T>() where T : new()
14         {
15             string fileName = @"E:\online_3\20150806第三期高级班Course10SerializeJson\Course10SerializeJson\Course10SerializeJson\file\Person.xml";//文件名称与路径
16             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
17             {
18                 XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
19                 return (T)xmlFormat.Deserialize(fStream);
20             }
21         }    
XmlSerializer
技术分享
 1         private static string CurrentDataPath = ConfigurationManager.AppSettings["CurrentDataPath"];
 2         public static void BinarySerialize()
 3         {
 4             //使用二进制序列化对象
 5             string fileName = Path.Combine(CurrentDataPath, @"BinarySerialize.txt");//文件名称与路径
 6             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 7             {
 8                 List<Programmer> pList = GetProgrammerList();
 9                 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
10                 binFormat.Serialize(fStream, pList);
11             }
12             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
13             {
14                 List<Programmer> pList = new List<Programmer>();
15                 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
16                 //使用二进制反序列化对象
17                 pList.Clear();//清空列表
18                 fStream.Position = 0;//重置流位置
19                 pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化对象
20             }
21         }    
BinaryFormatter
技术分享
 1  public static void SoapSerialize()
 2         {
 3             //使用Soap序列化对象
 4             string fileName = Path.Combine(CurrentDataPath, @"SoapSerialize.txt");//文件名称与路径
 5             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 6             {
 7                 List<Programmer> pList = GetProgrammerList();
 8                 SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
 9                 //soapFormat.Serialize(fStream, list);//SOAP不能序列化泛型对象
10                 soapFormat.Serialize(fStream, pList.ToArray());
11             }
12             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
13             {
14                 SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
15                 //使用二进制反序列化对象
16                 fStream.Position = 0;//重置流位置
17                 List<Programmer> pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList();//反序列化对象
18             }
19         }
SoapFormatter
技术分享
 1         public static void XmlSerialize()
 2         {
 3             //使用XML序列化对象
 4             string fileName = Path.Combine(CurrentDataPath, @"Student.xml");//文件名称与路径
 5             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 6             {
 7                 List<Programmer> pList = GetProgrammerList();
 8                 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
 9                 xmlFormat.Serialize(fStream, pList);
10             }
11             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
12             {
13                 List<Programmer> pList = new List<Programmer>();
14                 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
15                 //使用XML反序列化对象
16                 fStream.Position = 0;//重置流位置
17                 pList = (List<Programmer>)xmlFormat.Deserialize(fStream);
18             }
19         }
XmlSerializer

 

IO&Seralize