public class SerializationHelp
{
/// <summary>
/// 序列化二进制
/// </summary>
/// <param name="book"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool SerBinary(object obj, string path)
{
FileStream stream = new FileStream(path, FileMode.OpenOrCreate);
try
{
BinaryFormatter binary = new BinaryFormatter();
binary.Serialize(stream, obj);
return true;
}
catch (Exception ex)
{
throw;
}
finally {
stream.Close();
}
}
/// <summary>
/// 反序列化二进制
/// </summary>
/// <param name="book"></param>
/// <param name="path"></param>
/// <returns></returns>
public static object DeserBinary(string path)
{
FileStream stream = new FileStream(path, FileMode.Open);
object result;
try
{
if (stream == null)
{
throw (new Exception("该文件不存在"));
}
BinaryFormatter binary = new BinaryFormatter();
if (stream == null) {
throw (new Exception("该文件不存在"));
}
result = binary.Deserialize(stream);
return result;
}
catch (Exception)
{
throw;
}
finally {
stream.Close();
}
}
/// <summary>
/// 序列化SOAP
/// </summary>
/// <param name="obj"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool SerSoap(object obj, string path) {
FileStream stream = new FileStream(path, FileMode.OpenOrCreate);
try
{
SoapFormatter soap = new SoapFormatter();
soap.Serialize(stream, obj);
return true;
}
catch (Exception)
{
throw;
}
finally {
stream.Close();
}
}
/// <summary>
/// 反序列化SOAP
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static object DeserSOAP(string path) {
FileStream stream = new FileStream(path, FileMode.Open);
if (stream == null) {
throw (new Exception("该文件不存在"));
}
try
{
SoapFormatter soap = new SoapFormatter();
return soap.Deserialize(stream);
}
catch (Exception)
{
throw;
}
finally {
stream.Close();
}
}
public static bool SerXML(object obj,string path) {
FileStream stream = new FileStream(path, FileMode.OpenOrCreate);
try
{
XmlSerializer xml = new XmlSerializer(obj.GetType());
xml.Serialize(stream, obj);
return true;
}
catch (Exception)
{
throw;
}
finally {
stream.Close();
}
}
/// <summary>
/// xml反序列化
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static object DeserXML(string path,Type type) {
FileStream stream = new FileStream(path, FileMode.OpenOrCreate);
try
{
if (stream == null)
{
throw (new Exception("该文件不存在"));
}
XmlSerializer xml = new XmlSerializer(type);
return xml.Deserialize(stream);
}
catch (Exception)
{
throw;
}
finally {
stream.Close();
}
}
}