2013-08-21 57 views
0

我想創建一個將對象序列化到文件的方法。比我讀文件,並獲得內容爲字符串。我保存在數據庫中的字符串,比我讀了DB和我串去序列化到對象無法反序列化從字符串創建的流中的對象

我幾乎做到了,但我得到錯誤there is no map for object

這是我如何序列化對象

public static String Serialize(Object toSerialize) 
    { 
     Random random = new Random(); 
     int randomNumber = random.Next(100000, 1000000000); 
     String fileName = randomNumber + ".txt"; 

     fileName = "EmployeeInfo.txt"; 

     Stream stream = File.Open(fileName, FileMode.Create); 
     BinaryFormatter bformatter = new BinaryFormatter(); 

     bformatter.Serialize(stream, toSerialize); 
     stream.Close(); 

     String fileContent = File.ReadAllText(fileName); 

     return fileContent; 
    } 

這是我如何將字符串轉換爲流,用於反序列化

String serialized = Serializer.Serialize(user); 

     MemoryStream mStream = new MemoryStream(); 
     StreamWriter writer = new StreamWriter(mStream); 
     writer.Write(serialized); 
     writer.Flush(); 
     mStream.Position = 0; 

而現在的反序列化

public static Object Deserialize(Stream stream) 
    { 
     Object returnObject; 
     BinaryFormatter bformatter = new BinaryFormatter(); 
     returnObject = (Object)bformatter.Deserialize(stream); 
     stream.Close(); 

     return returnObject; 
    } 

我在哪裏犯錯?我應該做些什麼才能使它工作?

+0

什麼是你想要序列化的對象? – Tarec

+0

在哪條線上出現錯誤 –

+3

您無法用'ReadAllText'讀取二進制文件。使用'Convert.ToBase64String(File.ReadAllBytes(文件名))' – I4V

回答

0

得到了答案。

所有感謝@ I4V對他的評論首先:

這是我的Serialize方法

public static String Serialize(Object toSerialize) 
    { 
     Random random = new Random(); 
     int randomNumber = random.Next(100000, 1000000000); 
     String fileName = randomNumber + ".txt"; 

     fileName = "EmployeeInfo.txt"; 

     MemoryStream stream = new MemoryStream(); 

     BinaryFormatter bformatter = new BinaryFormatter(); 
     bformatter.Serialize(stream, toSerialize); 

     String fileContent = Convert.ToBase64String(stream.ToArray()); 
     stream.Close(); 

     return fileContent; 
    } 

現在方法反序列化可以從字符串

反序列化對象
public static Object Deserialize(String stringObject) 
    { 
     Object returnObject; 
     byte[] bytes = Convert.FromBase64String(stringObject); 

     MemoryStream stream = new MemoryStream(bytes); 

     BinaryFormatter bformatter = new BinaryFormatter(); 
     returnObject = bformatter.Deserialize(stream); 

     return returnObject; 
    } 

多數民衆贊成

相關問題