2013-01-31 105 views
0

我在獲取SOAP服務以反序列化對象數組時遇到問題;它在數組的第一個成員中唯一的讀數而沒有其他值。這裏是我的代碼:使用SOAP反序列化陣列

public void StoreCredentials(Credentials credentials) 
    { 
     Credentials[] credsArray; 
     var soap = new SoapFormatter(); 

     var stream = new FileStream(_path, FileMode.OpenOrCreate); 
     try 
     { 
      credsArray = (Credentials[])soap.Deserialize(stream); 
      var credsList = credsArray.ToList(); 
      credsList.Add(credentials); 
      credsArray = credsList.ToArray(); 
     } 
     catch (SerializationException) 
     { 
      credsArray = new[] {credentials}; 
     } 
     soap.Serialize(stream, credsArray); 
     stream.Close(); 
    } 

我寫了一個簡單的單元測試,增加了兩個證書對象的文件,輸出看起來正確的,證書的兩組都存在,但是當我運行測試增加第三組到文件中,soap.Deserialize(stream)行只返回一個只有一個條目的數組,即使它讀取的文件包含兩個條目。我在這裏做錯了什麼?有沒有更好/更簡單的方法來做到這一點?請幫忙!

+0

,你爲什麼和SOAPformatter玩?爲什麼不使用WCF,它會爲你做序列化? –

+0

它是一個學校的東西... – peter9464

+0

爲什麼你的學校讓你做愚蠢的事情? –

回答

0

我想通了。問題在於FileStream的FileMode.OpenOrCreate屬性。這將打開文件,但附加一個新的集合,而不是更改原始集合。我需要重寫使用FileMode.Create不是文件,所以這裏是工作的代碼(我也改變了收集到一個Hashtable,它工作得更好):

public void StoreCredentials(Credentials credentials) 
    { 
     credentials.Encrypt(_myUser.Encryption); 
     Hashtable credsTable; 
     var soap = new SoapFormatter(); 

     FileStream stream; 
     try 
     { 
      stream = new FileStream(_path, FileMode.Open, FileAccess.ReadWrite); 
      credsTable = (Hashtable) soap.Deserialize(stream); 
      stream.Close(); 
      stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite); 
      if (credsTable.ContainsKey(credentials.Id)) 
       credsTable[credentials.Id] = credentials; 
      else 
       credsTable.Add(credentials.Id, credentials); 
     } 
     catch (FileNotFoundException e) 
     { 
      stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite); 
      credsTable = new Hashtable {{credentials.Id, credentials}}; 
     } 
     soap.Serialize(stream, credsTable); 
     stream.Close(); 
    }