本案例主要实现以下几种方式的序列化与反序列化操作,可以通过设置SerializeType
参数进行切换
JSON
XML
- 二进制文件
using Newtonsoft.Json;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace IntelligentAssemblySystem.Helpers
{
public static class SerializeHelper
{
/// <summary>
/// 将对象序列化为指定文件
/// </summary>
/// <param name="instance"></param>
/// <param name="path"></param>
/// <param name="type"></param>
public static void Serialize(this object instance, string path, SerializeType type = SerializeType.Json)
{
// 先将文件进行备份后再进行存储
if (File.Exists(path))
{
string directoryName = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string extension = Path.GetExtension(path);
string backupDirectory = $"{directoryName}/backup/{fileName}/";
if (!Directory.Exists(backupDirectory)) Directory.CreateDirectory(backupDirectory);
string backupFileName = $"{backupDirectory}/{fileName}_{DateTime.Now:yyyy_MM_dd_HH_mm_ss}{extension}";
File.Copy(path, backupFileName, true);
}
else
{
// 若路径不存在,先检查文件夹是否存在,不存在则创建文件夹,再创建文件
string directoryName = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
Directory.CreateDirectory(directoryName);
File.Create(path).Close();
}
switch (type)
{
case SerializeType.Json:
{
File.WriteAllText(path, JsonConvert.SerializeObject(instance, Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
}));
break;
}
case SerializeType.Xml:
{
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
if (instance == null) throw new ArgumentNullException(@"instance");
XmlSerializer serializer = new XmlSerializer(instance.GetType());
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
NewLineChars = "\r\n",
Encoding = Encoding.UTF8,
IndentChars = " "
};
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, instance);
}
}
break;
}
case SerializeType.Binary:
{
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.ReadWrite);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, instance);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
fs.Close();
}
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
/// <summary>
/// 将文件反序列化为指定对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <param name="type"></param>
/// <returns></returns>
public static T Deserialize<T>(string path, SerializeType type = SerializeType.Json)
{
T t = default(T);
switch (type)
{
case SerializeType.Json:
{
t = JsonConvert.DeserializeObject<T>(File.ReadAllText(path), new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
break;
}
case SerializeType.Xml:
{
var serializer = new XmlSerializer(typeof(T));
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = XmlReader.Create(fs))
{
t = (T)serializer.Deserialize(reader);
}
}
break;
}
case SerializeType.Binary:
{
FileStream fs = new FileStream(path, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
try
{
t = (T)formatter.Deserialize(fs);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
fs.Close();
}
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
return t;
}
}
public enum SerializeType
{
/// <summary>
/// JSON格式
/// </summary>
Json,
/// <summary>
/// XML格式
/// </summary>
Xml,
/// <summary>
/// 二进制格式
/// </summary>
Binary
}
}