2012-11-05 42 views
0

我想反序列化我的「DataStore」以獲取一個Typs列表。首先,我想用XMLSerializer製作XMl中的文件,但似乎他不喜歡Interfaces,Abstract Class和Typs ......但沒有解決方法,因此我需要將我的主要內容存儲在XML類中:輸入流不是有效的二進制格式

public class InstalledObjects 
{ 
    private InstalledObjects() 
    { 

    } 

    static InstalledObjects _instance = new InstalledObjects(); 

    ObservableCollection<AbstrICTSUseObject> _installedObects = new ObservableCollection<AbstrICTSUseObject>();   

    public static InstalledObjects Instance 
    { 
     get { return _instance; } 
     set { _instance = value; } 
    } 

    public ObservableCollection<AbstrICTSUseObject> InstalledObects 
    { 
     get { return _installedObects; } 
     set { _installedObects = value; } 
    } 

    public void Saves() 
    { 
     List<Type> types = new List<Type>(); 

     foreach (var item in InstalledObects) 
     { 
      types.Add(item.GetType()); 
     } 

     TypeStore ts = new TypeStore(); 
     ts.Typen = types; 
     ts.SaveAsBinary("TypeStore.xml"); 
     this.SaveAsXML("LocalDataStore.xml", types.ToArray()); 
    } 

    public void Load() 
    { 
     if (File.Exists("LocalDataStore.xml")) 
     { 
      TypeStore ts = new TypeStore(); 
      ts.LoadFromBinary("LocalDataStore.xml"); 
      this.LoadFromXML("LocalDataStore.xml",ts.Typen.ToArray()); 
     } 
    } 
} 

和存儲我的Typs在一個簡單的類:

[Serializable] 
public class TypeStore 
{ 
    List<Type> _typen = new List<Type>(); 

    public List<Type> Typen 
    { 
     get { return _typen; } 
     set { _typen = value; } 
    } 
} 

好啊好啊覺得只要我只是保存所有這工作,我認爲這也將工作,如果有不會的豆蔻問題,即「LoadFromBinary」拋出一些期待 - .-

public static void SaveAsBinary(this Object A, string FileName) 
    { 
     FileStream fs = new FileStream(FileName, FileMode.Create); 
     BinaryFormatter formatter = new BinaryFormatter(); 
     formatter.Serialize(fs, A); 
    } 

    public static void LoadFromBinary(this Object A, string FileName) 
    { 
     if (File.Exists(FileName)) 
     { 
      Stream fs = new FileStream(FileName, FileMode.Open); 
      BinaryFormatter formatter = new BinaryFormatter(); 
      A = formatter.Deserialize(fs) ; 
     } 
    } 

的Expeption:

 The input stream is not a valid binary format. The starting contents (in bytes) are: 3C-3F-78-6D-6C-20-76-65-72-73-69-6F-6E-3D-22-31-2E ... 

THX的幫助Venson :-)

回答

1

這是簡單的事實,即你從錯誤的文件讀取?

注:

ts.SaveAsBinary("TypeStore.xml"); 
this.SaveAsXML("LocalDataStore.xml", types.ToArray()); 

然後:

ts.LoadFromBinary("LocalDataStore.xml"); 
this.LoadFromXML("LocalDataStore.xml", ts.Typen.ToArray()); 

應該是:

ts.LoadFromBinary("TypeStore.xml"); 
this.LoadFromXML("LocalDataStore.xml", ts.Typen.ToArray()); 

但是,請注意,調用它.XML是一種誤導。另外:注意版本 - BinaryFormatter是一個真正的豬。就個人而言,我只是手動序列化每種類型的AssemblyQualifiedName - 這可以在正常的XML中完成。

+0

Oh DAMMED thx rly BAD c&p failure ... Thx – Venson

相關問題