2012-11-05 18 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

相关问题