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

                              ------------------------Anker_张(博客园)http://www.cnblogs.com/AnkerZhang/

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 = "";
byte[] bytes = Encoding.Default.GetBytes(name);
fileStream.Write(bytes, , bytes.Length);
fileStream.Flush();
}
using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入)
{
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine("");
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 = "";
byte[] bytes = Encoding.Default.GetBytes(name);
sw.BaseStream.Write(bytes, , 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 = ;
int result = ; do
{
byte[] bytes = new byte[length];
result = stream.Read(bytes, , );
for (int i = ; 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 = ;//重置流位置
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 = ;//重置流位置
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 = ;//重置流位置
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 > )
{
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(, ) + propinfo.Name.Substring(, propinfo.Name.Length - );
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 = ;
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;
}
*/
}
序列化或反序列化成一个字符串:
public static string XMLSerialize<T>(T entity)
{
StringBuilder buffer = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer))
{
serializer.Serialize(writer, entity);
} return buffer.ToString(); }
反序列化:
public static T DeXMLSerialize<T>(string xmlString)
{
T cloneObject = default(T); StringBuilder buffer = new StringBuilder();
buffer.Append(xmlString); XmlSerializer serializer = new XmlSerializer(typeof(T)); using (TextReader reader = new StringReader(buffer.ToString()))
{
Object obj = serializer.Deserialize(reader);
cloneObject = (T)obj;
} return cloneObject;
}

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

  1. javascript jsscript .js xml html json soap

    javascript ecma标准的脚本语言用于 jsscript 微软标准的一种脚本语言 .js javascript或jsscript保存成文件的形式可用于在html里重复引用 jsscript只 ...

  2. 10分钟掌握XML、JSON及其解析

    引言 NOKIA 有句著名的广告语:“科技以人为本”.任何技术都是为了满足人的生产生活需要而产生的.具体到小小的一个手机,里面蕴含的技术也是浩如烟海,是几千年来人类科技的结晶,单个人穷其一生也未必能掌 ...

  3. Python: xml转json

    1,引言 GooSeeker早在9年前就开始了Semantic Web领域的产品化,MS谋数台和DS打数机是其中两个产品.对web内容做结构化转换和语义处理的主要路线是 XML -> RDF - ...

  4. xml 和json 数据格式及解析

    来源:http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”.任何技术都是为了满足人的生产生活需要而产生的.具体到小小的一个手机,里面蕴含的 ...

  5. 数据格式XML、JSON详解

    一. XML数据格式 1.1 XML的定义  扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类 ...

  6. 数据解析(XML和JSON数据结构)

    一   解析 二 XML数据结构 三 JSON 数据结构     一 解析 1  定义: 从事先规定好的格式中提取数据     解析的前提:提前约定好格式,数据提供方按照格式提供数据.数据获取方则按照 ...

  7. 【原】iOS学习之XML与JSON两种数据结构比较和各自底层实现

    1.XML与JSON两种数据结构的优缺点 1> XML 优点:
 格式统一, 符合标准
 容易与其他系统进行远程交互, 数据共享比较方便 
 缺点: XML文件格式文件庞大, 格式复杂, 传输占 ...

  8. XML与JSON的对比

    XML与JSON的对比 1.各自定义 XML 扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类 ...

  9. UI:数据的解析XML与JSON

    XML  和  JSON 语言  本篇博客来自互联网参考 XML 和 JSON 的互相转化 有属性的转化为对象,无属性的转化为字符串 节点的顺序性不可逆,XML有顺序,JSON 无顺序 XML 和 J ...

  10. SpringBoot Xml转Json对象

    一.导入需要的依赖 <dependency> <groupId>maven</groupId> <artifactId>dom4j</artifa ...

随机推荐

  1. toitorsegit and toitorstsvn文件夹icon冲突不显示

    Go to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer Add a new string value & ...

  2. 2017-2018-1 20179209《Linux内核原理与分析》第二周作业

    本周课业主要通过分析汇编代码执行情况掌握栈的变化.本人本科时期学过intel 80X86汇编语言,所以有一定基础:在Linux中32位AT&T风格的汇编稍微熟悉就可以明白.所以我学习的重点放在 ...

  3. Tomcat学习笔记【5】--- 项目部署详解

    本文主要讲在Tomcat中部署项目的几种方式:静态部署.动态部署. 一 静态部署 静态部署项目有好几种方式,比较典型的有如下4种: 1.1 方式一:将Web项目放到webApps目录下 直接将web项 ...

  4. ubuntu安装opencv(自己编译)

    如果只需要python的,只需pip install opencv-python,然后apt-get一下下面第一点的东东. 1/ sudo apt-get install build-essentia ...

  5. spring cloud初识

    spring cloud是spring中的一个快速开发框架.本实例采用spring+maven来配置一个简单的spring开发实例. 1.首先安装java和maven环境. ①.安装java,不做过多 ...

  6. Compiling: main.cpp /bin/sh: g++: not found

    Kbuntu用codeblocks编写C程序的时候,编译报错如下: Compiling: main.cpp/bin/sh: g++: not found 解决方法: sudo apt-get inst ...

  7. 使用.net实现ZooKeeper客户端

    最近在项目中用到ZooKeeper, 通过Java连接比较容易,.net项目就没那么容易,尤其对于不熟悉Linux的开发人员,这里写点搭建ZooKeeper测试环境的经验,供参考. 背景知识: Zoo ...

  8. Mac系统存储-其他存储无故增大

    解决办法:打开Finder:安全倾倒废纸篓就会减少很大一部分存储.

  9. C#多线程编程介绍——使用thread、threadpool、timer

    C#多线程编程介绍——使用thread.threadpool.timer 在system.threading 命名空间提供一些使得能进行多线程编程的类和接口,其中线程的创建有以下三种方法:thread ...

  10. composer镜像安装laravel

    博主最近在学习Laravel的框架的相关知识,对于Laravel的许多新特性,大家最好还是去查看官网文档最好,Laravel的文档非常完善,中文英文的都有,可以很好的解决你的困惑. 但是我们会发现学习 ...