- public class SerializeHelper
- {
- #region 二进制格式
- /// <summary>
- /// Binary 序列化使用前需要标记类可序列化
- /// </summary>
- /// <param name="fileName">序列化到指定的文件</param>
- /// <param name="obj">需要序列化的类</param>
- public static void BinarySerializer<T>(T obj, string fileName) where T : class
- {
- using (Stream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
- {
- try
- {
- if (!Directory.GetParent(fileName).Exists)
- {
- Directory.GetParent(fileName).Create();
- }
- BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
- binFormat.Serialize(fStream, obj);
- fStream.Close();
- }
- catch (Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("二进制文件序列化错误: " + ex.ToString(), Color.Red, "Main");
- }
- }
- }
- /// <summary>
- /// Binary 反序列化使用前需要标记类可序列化
- /// </summary>
- /// <param name="filePath">从指定的文件序列化成相应对象</param>
- /// <returns>反序列化后的类对象通过泛型限定</returns>
- public static T BinaryDeserializer<T>(string fileName)
- {
- T obj = default(T);
- if (System.IO.File.Exists(fileName))//检查文件是否存在
- {
- using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
- {
- try
- {
- fs.Position = 0;
- BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
- obj = (T)binFormat.Deserialize(fs);
- fs.Close();
- return obj;
- }
- catch (System.Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("二进制文件反序列化错误:" + ex.ToString(), Color.Red,"Main");
- MessageBox.Show("二进制文件反序列化错误:" + fileName + ex.ToString(),"Main");
- }
- }
- }
- return obj;
- }
- #endregion
- #region Json 格式
- /// <summary>
- /// 反序列化json文件
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns>反序列化后的类对象通过泛型限定</returns>
- public static T DeserializeJson<T>(string fileName)
- {
- T obj = default(T);
- try
- {
- if (!File.Exists(fileName)) return obj;
- return JsonConvert.DeserializeObject<T>(File.ReadAllText(fileName));
- }
- catch (Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("Json文件序列化错误: " + ex.ToString(), Color.Red, "Main");
- }
- return obj;
- }
- /// <summary>
- /// 序列化json文件
- /// </summary>
- /// <typeparam name="T">序列化限定的泛型</typeparam>
- /// <param name="fileName">文件路径</param>
- public static void SerializeJson<T>(T obj, string fileName) where T : class
- {
- try
- {
- string dir = fileName.Substring(0, fileName.LastIndexOf('\\'));
- if (!Directory.Exists(dir))
- {
- Directory.CreateDirectory(dir);
- }
- var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
- var json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, jsonSetting);
- File.WriteAllText(fileName, json);
- }
- catch (Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("Json文件反序列化错误: " + ex.ToString(), Color.Red, "Main");
- }
- }
- #endregion
- #region XML格式
- /// <summary>
- ///
- ///《/summary>
- /// <typeparam name="T">限定的泛型类型</typeparam>
- /// <param name="fileName">文件路径</param>
- /// <param name="obj">序列化的对象</param>
- /// <param name="omitXmlDeclaration">是否需要xml版本描述</param>
- /// <param name="removeDefaultNameSpace">是否从新开始添加</param>
- public static void XmlSerialize<T>(string fileName, T obj, bool omitXmlDeclaration, bool removeDefaultNameSpace)
- {
- try
- {
- XmlWriterSettings xmlSetting = new XmlWriterSettings();
- xmlSetting.OmitXmlDeclaration = omitXmlDeclaration;
- xmlSetting.Indent = true;
- xmlSetting.Encoding = new UTF8Encoding(false);
- xmlSetting.NewLineChars = Environment.NewLine;
- using (XmlWriter xmlWriter = XmlWriter.Create(fileName, xmlSetting))
- {
- XmlSerializerNamespaces xmlms = new XmlSerializerNamespaces();
- if (removeDefaultNameSpace)
- {
- xmlms.Add(string.Empty, string.Empty);
- }
- XmlSerializer ser = new XmlSerializer(typeof(T));
- ser.Serialize(xmlWriter, obj, xmlms);
- }
- }
- catch (Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("XML文件序列化错误: " + ex.ToString(), Color.Red, "Main");
- }
- }
- /// <summary>
- /// xml反序列化
- /// </summary>
- /// <typeparam name="T">限定的泛型类型</typeparam>
- /// <param name="fileName">文件路径</param>
- /// <returns>返回限定的泛型类</returns>
- public static T XmlDeserialize<T>(string fileName) where T : class
- {
- try
- {
- XmlReaderSettings xmlReaderSetting = new XmlReaderSettings();
- xmlReaderSetting.CloseInput = true;
- using (XmlReader xmlReader = XmlReader.Create(fileName, xmlReaderSetting))
- {
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- return (T)xmlSerializer.Deserialize(xmlReader);
- }
- }
- catch (Exception ex)
- {
- //HelperEvent.OnMessageColor?.Invoke("XML文件反序列化错误: " + ex.ToString(), Color.Red, "Main");
- return null;
- }
- }
- #endregion
- }
复制代码 对象序列化需要在类上面加上[Serializable]
调用:path是程序的exe目录,data是序列化文件的
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |