C# Note4:XML序列化和反序列化(含加密解密等)

时间:2024-03-22 12:05:08

前言

在项目中,我们经常用到各种配置文件,比如xml文件、binary文件等等,这里主要根据实践经验介绍下xml文件的序列化和反序列化(毕竟最常用)。

实践背景:我要做一个用户管理功能,用户账号信息存储在xml/binary文件中,需要对其进行读写,而且为了不让用户修改,必须对其加密,当时想的有3种做法:

(1)实现读写xml配置文件,并将关键信息加密;

(2)实现读写binary配置文件,并将关键信息加密;

(3)直接对配置文件进行加密解密和读写,不管它所使用的文件格式是xml、binary或其它。

这三种做法我都实现了,不过经过最后manager的确认觉得采用第(3)种方法最好。

方法一:

(推荐:Load and save objects to XML using serialization  本方法参考其思路)

(1)在我们将对象序列化为XML之前,对象的类代码必须包含各种自定义元数据属性(例如,[XmlAttributeAttribute(DataType = " date "])告诉编译器类及其字段和/或属性可以被序列化。

using System;
using System.Xml.Serialization;
using System.Collections.ObjectModel; namespace XXX.GlobalTypes
{
/// <summary>
/// Save user account information
/// </summary>
[Serializable]
[XmlRoot("UserManagement")]
public class UserAccountInfo
{
private readonly Collection<UserInfo> _users = new Collection<UserInfo>(); [XmlElement("UserAccountInfo")]
public Collection<UserInfo> Users
{
get { return this._users; }
}
} [Serializable]
public class UserInfo
{ [XmlElement("UserName")]
public string UserName
{
get;
set;
} [XmlElement("UserPwd")]
public string UserPwd
{
get;
set;
} [XmlElement("UserRole")]
public ACCESS_LEVEL UserRole
{
get;
set;
} [XmlElement("Description")]
public string Description
{
get;
set;
}
} }

(2)封装XML序列化的类(其中作为样例,我加入了加密解密的参数tDESkey,在将数据对象保存到xml文件后进行加密,从xml文件中读取数据前先进行解密):

 using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml.Serialization; // For serialization of an object to an XML Document file.
using System.Runtime.Serialization.Formatters.Binary; // For serialization of an object to an XML Binary file.
using System.IO; // For reading/writing data to an XML file.
using System.IO.IsolatedStorage; // For accessing user isolated data. namespace XXX.Utilities.Common
{
/// <summary>
/// Serialization format types.
/// </summary>
public enum SerializedFormat
{
/// <summary>
/// Binary serialization format.
/// </summary>
Binary, /// <summary>
/// Document serialization format.
/// </summary>
Document
} /// <summary>
/// Facade to XML serialization and deserialization of strongly typed objects to/from an XML file.
///
/// References: XML Serialization at http://samples.gotdotnet.com/:
/// http://samples.gotdotnet.com/QuickStart/howto/default.aspx?url=/quickstart/howto/doc/xmlserialization/rwobjfromxml.aspx
/// </summary>
public static class ObjectXMLSerializer<T> where T : class // Specify that T must be a class.
{
#region Load methods /// <summary>
/// Loads an object from an XML file in Document format.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load(@"C:\XMLObjects.xml");
/// </code>
/// </example>
/// <param name="path">Path of the file to load the object from.</param>
/// <returns>Object loaded from an XML file in Document format.</returns>
public static T Load(string path, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = LoadFromDocumentFormat(null, path, null, tDESkey);
return serializableObject;
} /// <summary>
/// Loads an object from an XML file using a specified serialized format.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load(@"C:\XMLObjects.xml", SerializedFormat.Binary);
/// </code>
/// </example>
/// <param name="path">Path of the file to load the object from.</param>
/// <param name="serializedFormat">XML serialized format used to load the object.</param>
/// <returns>Object loaded from an XML file using the specified serialized format.</returns>
public static T Load(string path, SerializedFormat serializedFormat, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = null; switch (serializedFormat)
{
case SerializedFormat.Binary:
serializableObject = LoadFromBinaryFormat(path, null);
break; case SerializedFormat.Document:
default:
serializableObject = LoadFromDocumentFormat(null, path, null, tDESkey);
break;
} return serializableObject;
} /// <summary>
/// Loads an object from an XML file in Document format, supplying extra data types to enable deserialization of custom types within the object.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load(@"C:\XMLObjects.xml", new Type[] { typeof(MyCustomType) });
/// </code>
/// </example>
/// <param name="path">Path of the file to load the object from.</param>
/// <param name="extraTypes">Extra data types to enable deserialization of custom types within the object.</param>
/// <returns>Object loaded from an XML file in Document format.</returns>
public static T Load(string path, System.Type[] extraTypes, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = LoadFromDocumentFormat(extraTypes, path, null, tDESkey);
return serializableObject;
} /// <summary>
/// Loads an object from an XML file in Document format, located in a specified isolated storage area.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load("XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly());
/// </code>
/// </example>
/// <param name="fileName">Name of the file in the isolated storage area to load the object from.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to load the object from.</param>
/// <returns>Object loaded from an XML file in Document format located in a specified isolated storage area.</returns>
public static T Load(string fileName, IsolatedStorageFile isolatedStorageDirectory, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = LoadFromDocumentFormat(null, fileName, isolatedStorageDirectory, tDESkey);
return serializableObject;
} /// <summary>
/// Loads an object from an XML file located in a specified isolated storage area, using a specified serialized format.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load("XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly(), SerializedFormat.Binary);
/// </code>
/// </example>
/// <param name="fileName">Name of the file in the isolated storage area to load the object from.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to load the object from.</param>
/// <param name="serializedFormat">XML serialized format used to load the object.</param>
/// <returns>Object loaded from an XML file located in a specified isolated storage area, using a specified serialized format.</returns>
public static T Load(string fileName, IsolatedStorageFile isolatedStorageDirectory, SerializedFormat serializedFormat, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = null; switch (serializedFormat)
{
case SerializedFormat.Binary:
serializableObject = LoadFromBinaryFormat(fileName, isolatedStorageDirectory);
break; case SerializedFormat.Document:
default:
serializableObject = LoadFromDocumentFormat(null, fileName, isolatedStorageDirectory, tDESkey);
break;
} return serializableObject;
} /// <summary>
/// Loads an object from an XML file in Document format, located in a specified isolated storage area, and supplying extra data types to enable deserialization of custom types within the object.
/// </summary>
/// <example>
/// <code>
/// serializableObject = ObjectXMLSerializer&lt;SerializableObject&gt;.Load("XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly(), new Type[] { typeof(MyCustomType) });
/// </code>
/// </example>
/// <param name="fileName">Name of the file in the isolated storage area to load the object from.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to load the object from.</param>
/// <param name="extraTypes">Extra data types to enable deserialization of custom types within the object.</param>
/// <returns>Object loaded from an XML file located in a specified isolated storage area, using a specified serialized format.</returns>
public static T Load(string fileName, IsolatedStorageFile isolatedStorageDirectory, System.Type[] extraTypes, TripleDESCryptoServiceProvider tDESkey)
{
T serializableObject = LoadFromDocumentFormat(null, fileName, isolatedStorageDirectory, tDESkey);
return serializableObject;
} #endregion #region Save methods /// <summary>
/// Saves an object to an XML file in Document format.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, @"C:\XMLObjects.xml");
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="path">Path of the file to save the object to.</param>
public static void Save(T serializableObject, string path, TripleDESCryptoServiceProvider tDESkey)
{
SaveToDocumentFormat(serializableObject, null, path, null, tDESkey);
} /// <summary>
/// Saves an object to an XML file using a specified serialized format.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, @"C:\XMLObjects.xml", SerializedFormat.Binary);
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="path">Path of the file to save the object to.</param>
/// <param name="serializedFormat">XML serialized format used to save the object.</param>
public static void Save(T serializableObject, string path, SerializedFormat serializedFormat, TripleDESCryptoServiceProvider tDESkey)
{
switch (serializedFormat)
{
case SerializedFormat.Binary:
SaveToBinaryFormat(serializableObject, path, null);
break; case SerializedFormat.Document:
default:
SaveToDocumentFormat(serializableObject, null, path, null, tDESkey);
break;
}
} /// <summary>
/// Saves an object to an XML file in Document format, supplying extra data types to enable serialization of custom types within the object.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, @"C:\XMLObjects.xml", new Type[] { typeof(MyCustomType) });
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="path">Path of the file to save the object to.</param>
/// <param name="extraTypes">Extra data types to enable serialization of custom types within the object.</param>
public static void Save(T serializableObject, string path, System.Type[] extraTypes, TripleDESCryptoServiceProvider tDESkey)
{
SaveToDocumentFormat(serializableObject, extraTypes, path, null, tDESkey);
} /// <summary>
/// Saves an object to an XML file in Document format, located in a specified isolated storage area.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, "XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly());
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="fileName">Name of the file in the isolated storage area to save the object to.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to save the object to.</param>
public static void Save(T serializableObject, string fileName, IsolatedStorageFile isolatedStorageDirectory, TripleDESCryptoServiceProvider tDESkey)
{
SaveToDocumentFormat(serializableObject, null, fileName, isolatedStorageDirectory, tDESkey);
} /// <summary>
/// Saves an object to an XML file located in a specified isolated storage area, using a specified serialized format.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, "XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly(), SerializedFormat.Binary);
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="fileName">Name of the file in the isolated storage area to save the object to.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to save the object to.</param>
/// <param name="serializedFormat">XML serialized format used to save the object.</param>
public static void Save(T serializableObject, string fileName, IsolatedStorageFile isolatedStorageDirectory, SerializedFormat serializedFormat, TripleDESCryptoServiceProvider tDESkey)
{
switch (serializedFormat)
{
case SerializedFormat.Binary:
SaveToBinaryFormat(serializableObject, fileName, isolatedStorageDirectory);
break; case SerializedFormat.Document:
default:
SaveToDocumentFormat(serializableObject, null, fileName, isolatedStorageDirectory, tDESkey);
break;
}
} /// <summary>
/// Saves an object to an XML file in Document format, located in a specified isolated storage area, and supplying extra data types to enable serialization of custom types within the object.
/// </summary>
/// <example>
/// <code>
/// SerializableObject serializableObject = new SerializableObject();
///
/// ObjectXMLSerializer&lt;SerializableObject&gt;.Save(serializableObject, "XMLObjects.xml", IsolatedStorageFile.GetUserStoreForAssembly(), new Type[] { typeof(MyCustomType) });
/// </code>
/// </example>
/// <param name="serializableObject">Serializable object to be saved to file.</param>
/// <param name="fileName">Name of the file in the isolated storage area to save the object to.</param>
/// <param name="isolatedStorageDirectory">Isolated storage area directory containing the XML file to save the object to.</param>
/// <param name="extraTypes">Extra data types to enable serialization of custom types within the object.</param>
public static void Save(T serializableObject, string fileName, IsolatedStorageFile isolatedStorageDirectory, System.Type[] extraTypes, TripleDESCryptoServiceProvider tDESkey)
{
SaveToDocumentFormat(serializableObject, null, fileName, isolatedStorageDirectory, tDESkey);
} #endregion #region Private private static FileStream CreateFileStream(IsolatedStorageFile isolatedStorageFolder, string path)
{
FileStream fileStream = null; if (isolatedStorageFolder == null)
fileStream = new FileStream(path, FileMode.OpenOrCreate);
else
fileStream = new IsolatedStorageFileStream(path, FileMode.OpenOrCreate, isolatedStorageFolder); return fileStream;
} private static T LoadFromBinaryFormat(string path, IsolatedStorageFile isolatedStorageFolder)
{
T serializableObject = null; using (FileStream fileStream = CreateFileStream(isolatedStorageFolder, path))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
serializableObject = binaryFormatter.Deserialize(fileStream) as T;
} return serializableObject;
} private static T LoadFromDocumentFormat(System.Type[] extraTypes, string path, IsolatedStorageFile isolatedStorageFolder, TripleDESCryptoServiceProvider tDESkey)
{
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.PreserveWhitespace = true; xmlDoc.Load(path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
} // Decrypt the "UserManagement" element.
EncryptXml.Decrypt(xmlDoc, tDESkey);
xmlDoc.Save(path); T serializableObject = null; using (TextReader textReader = CreateTextReader(isolatedStorageFolder, path))
{
XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
serializableObject = xmlSerializer.Deserialize(textReader) as T;
} EncryptXml.Encrypt(xmlDoc, "UserManagement", tDESkey);
xmlDoc.Save(path); return serializableObject;
} private static TextReader CreateTextReader(IsolatedStorageFile isolatedStorageFolder, string path)
{
TextReader textReader = null; if (isolatedStorageFolder == null)
textReader = new StreamReader(path);
else
textReader = new StreamReader(new IsolatedStorageFileStream(path, FileMode.Open, isolatedStorageFolder)); return textReader;
} private static TextWriter CreateTextWriter(IsolatedStorageFile isolatedStorageFolder, string path)
{
TextWriter textWriter = null; if (isolatedStorageFolder == null)
textWriter = new StreamWriter(path);
else
textWriter = new StreamWriter(new IsolatedStorageFileStream(path, FileMode.OpenOrCreate, isolatedStorageFolder)); return textWriter;
} private static XmlSerializer CreateXmlSerializer(System.Type[] extraTypes)
{
Type ObjectType = typeof(T); XmlSerializer xmlSerializer = null; if (extraTypes != null)
xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
else
xmlSerializer = new XmlSerializer(ObjectType); return xmlSerializer;
} private static void SaveToDocumentFormat(T serializableObject, System.Type[] extraTypes, string path, IsolatedStorageFile isolatedStorageFolder, TripleDESCryptoServiceProvider tDESkey)
{
using (TextWriter textWriter = CreateTextWriter(isolatedStorageFolder, path))
{
XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
xmlSerializer.Serialize(textWriter, serializableObject); textWriter.Close(); XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.PreserveWhitespace = true; xmlDoc.Load(path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
} EncryptXml.Encrypt(xmlDoc, "UserManagement", tDESkey); xmlDoc.Save(path);
}
} private static void SaveToBinaryFormat(T serializableObject, string path, IsolatedStorageFile isolatedStorageFolder)
{
using (FileStream fileStream = CreateFileStream(isolatedStorageFolder, path))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, serializableObject);
}
} #endregion
}
}

(3)Saving an object to an XML file/Loading an object from an XML file

// Load the userManagement object from the XML file using our UserAccountInfo class...
UserAccountInfo userManagement =ObjectXMLSerializer<UserAccountInfo>.Load(path, tDESkey); // Load the userManagement object from the XML file using our userManagement class...
ObjectXMLSerializer<UserAccountInfo>.Save(usermanagement, XML_FILE_NAME, tDESkey);

方法二:

其实,要想仅仅实现xml的序列化和反序列化还是很简单的,作为常用的类,可以很简单地将其实现为公共类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization; namespace XXX.Common
{
public static class XmlHelper
{
public static object DeserializeObject<T>(string filePath)
{
try
{
var xs = new XmlSerializer(typeof(T));
using (var fs = new FileStream(filePath, FileMode.Open))
{
var reader = XmlReader.Create(fs);
return xs.Deserialize(reader);
}
}
catch (Exception exp)
{
throw new XmlException($"Failed in XML Deserialization {filePath}", exp);
}
} public static void SerializeObject<T>(string filePath, T o)
{
try
{
var x = new XmlSerializer(typeof(T));
using (var fs = new FileStream(filePath, FileMode.Create))
{
var writer = XmlWriter.Create(fs);
x.Serialize(writer, o);
}
}
catch (Exception exp)
{
throw new XmlException($"Failed in XML Serialization {filePath}", exp);
}
}
}
}

  

 

另可参考文章:

1.XML序列化和反序列化

2.在.net中读写config文件的各种方法