2013-03-21 89 views
0

我試圖通過使用DataContractSerializer反序列化文件。我有這樣的類:多根元素(DataContractSerializer)

[DataContract] 
public class kontenerUstawienia 
{ 
    [DataMember] 
    public int[] stanGry; 
    [DataMember] 
    public int maxSize; 
    [DataMember] 
    public int[] stanOpcji; 

    [DataMember] 
    public int numerFlagi1; 
    [DataMember] 
    public int numerFlagi2; 

    public kontenerUstawienia() 
    { 
    } 

(...) 
} 

內部,以節省序列化類實例的文件後,我讀了文件,並嘗試反序列化:

try 
{ 
    zapiszObiektUstawien((kontenerUstawienia)deserializer.ReadObject(strumien)); 
} 

catch (SerializationException e) 
{ 
    System.Diagnostics.Debug.WriteLine("\n\n\n\n++++++\n" + 
    e.Message 
    + "\n+++++++++++++++++++++++++++++++++++++++++++++++"); 
} 

抓打印我:

++++++ 
There was an error deserializing the object of type 
WindowsPhoneGame1.kontenerUstawienia. There are multiple root elements. Line 1, 
position 599. 
+++++++++++++++++++++++++++++++++++++++++++++++ 

我究竟做錯了什麼?

編輯: 這裏是我序列化和節省代碼:

public void zapiszDoPliku(string sciezkaDoPliku, IsolatedStorageFile katalog) 
{ 
    IsolatedStorageFileStream strumien = katalog.CreateFile(sciezkaDoPliku); // tworzenie pliku 

    MemoryStream ms = new MemoryStream(); 
    StreamReader r = new StreamReader(ms); 

    DataContractSerializer serializer = new DataContractSerializer(typeof(kontenerUstawienia)); 

    serializer.WriteObject(ms, this); 

    ms.Position = 0; 

    string daneDoZapisania = r.ReadToEnd(); 

    byte[] bytes = Encoding.Unicode.GetBytes(daneDoZapisania); 

    strumien.Write(bytes, 0, bytes.Length); 

    ms.Close(); 
    strumien.Close(); 
} 

EDIT2:

文件保存: File is here

+0

請顯示執行序列化的代碼。 – 2013-03-21 11:00:38

+0

我添加了序列化代碼 – 2013-03-21 11:11:30

+0

很可能你多次寫入'IsolatedStorageFile'而不刪除舊內容。 – 2013-03-21 11:13:33

回答

1

你確定該文件是在寫之前是空的?

+0

我正在使用CreateFile,而不是OpenFile,因此我認爲它會將其擦除。 – 2013-03-21 11:29:09

+0

在Close()流對象之前使用Flush()方法。 – 2013-03-22 10:18:37