这是我用来反序列化的两个函数,一个来自networkStream,另一个来自文件流
public static FileInfo recMetaSerialized(Socket s)
{
FileInfo o = null;
try {
BinaryFormatter bf = new BinaryFormatter();
NetworkStream stm = new NetworkStream(s);
o = (FileInfo)bf.Deserialize(stm);
Console.WriteLine("File info received recMetaSerialized: " + o.FullName + o.LastWriteTime);
return o;
}
catch(Exception e)
{
Console.WriteLine("Error in deserialization from the network. " +e.Message + e.StackTrace);
}
return null;
}
public static FileInfo readMetaSerialized(string file)
{
FileInfo o = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stm = new FileStream(file,FileMode.Open);
o = (FileInfo)bf.Deserialize(stm);
Console.WriteLine("File info received readMetaSerialized : " + o.FullName + o.LastWriteTime);
return o;
}
catch (Exception e)
{
Console.WriteLine("Error in deserialization from the file. " + e.Message + e.StackTrace);
}
return null;
}
我收到一些错误,因为FileInfo的FullName属性被正确打印出来,而LastWriteTime是错误的。在序列化对象的函数中,属性被正确序列化。
public static void saveMetaSerialized(string file, FileInfo obj)
{
if (obj == null)
throw new Exception("Error! File info obj is null!");
Console.WriteLine("File info received saveMetaSerialized: " + obj.FullName + obj.LastWriteTime);
BinaryFormatter bf = new BinaryFormatter();
try {
using (FileStream ms = new FileStream(file, FileMode.Create))
{
bf.Serialize(ms, obj);
}
}
catch (Exception e)
{
Console.WriteLine("Error in file ser of file {0} : {1}", obj.Name, e.Message);
}
Console.WriteLine("Serialization over the net of file {0} completed.", obj.Name);
}
public static void sendMetaSerialized(Socket s, string file)
{
FileInfo fi = new FileInfo(file);
Console.WriteLine("File info received sendMetaSerialized: " + fi.FullName + fi.LastWriteTime);
BinaryFormatter bf = new BinaryFormatter();
try {
bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
NetworkStream stm = new NetworkStream(s);
bf.Serialize(stm, fi);
}
catch (Exception e)
{
Console.WriteLine("Error in net ser of file {0} : {1}", fi.Name, e.Message);
}
Console.WriteLine("Serialization over the net of file {0} completed.", fi.Name);
}