一種序列化為binary型式
一種序列化為xml型式
另一種序列化為json型式
其中json型式沒有支援輸出檔案,要自己做
本篇用binaryformat序列化法
[Serializable]
class MessageEvent: ISerializable
{
public MessageEvent(SerializationInfo info, StreamingContext context) {
message= (string)info.GetValue("message", typeof(string));
timestamp = (long)info.GetValue("timestamp", typeof(long));//typeof型態要符合變數型態,否則會報TargetInvocationException
property = (string)info.GetValue("property", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("label",variable);
info.AddValue("label",variable);
info.AddValue("label",variable);
}
}
序列化:
MessageEvent mesEvent= new MessageEvent("hello earth",100L,"new");
string FILE_DIRECTORY = "D:\\SerializeFile\\";
DateTime saveNow = DateTime.Now;
String fileTimestamp = saveNow.ToString(("yyyyMMddHHmmssfff"));
BinaryFormatter serializer = new BinaryFormatter();
FileStream file = new FileStream(FILE_DIRECTORY+fileTimestamp+".txt", FileMode.Create);
serializer.Serialize(file, mesEvent);
file.Close();
反序列化:
public static void DeserializeFile() {
while (true)
{
string[] filesnames = Directory.GetFiles(FILE_DIRECTORY);
foreach (string filename in filesnames)
{
if(File.Exists(filename)){
MessageEvent resultMesEvent = null;
FileStream file = null;
try
{
BinaryFormatter serializer = new BinaryFormatter();
file = new FileStream(filename,FileMode.Open);
resultMesEvent = (MessageEvent)serializer.Deserialize(file);
Console.WriteLine("Serialize Success");
}
catch (TargetInvocationException ex) {
Console.WriteLine("please check serialized obj construct");
}
catch (System.IO.IOException ioe)
{
Console.WriteLine(ioe);
}
finally {
file.Close();
File.Delete(filename);//file.Close之後才delete
}
}
}
}
}