2011-06-24 97 views
3

我有以下System.Collections.Specialized.NameValueCollection實例:如何將System.Collections.Specialized.NameValueCollection實例保存到硬盤並作爲實例加載回來?

Dim UserSelection As New System.Collections.Specialized.NameValueCollection 

UserSelection.Add("D_Color1", "Black") 
UserSelection.Add("D_Color2", "Green") 
UserSelection.Add("D_Color3", "Purple") 

我需要保存這個實例的硬盤,然後加載它從硬盤恢復作爲一個實例。我怎麼做?

+1

爲什麼要一個字節數組?如果你需要它反序列化到一個不需要字節數組的NameValueCollection。 – RyanR

+0

xml怎麼樣?它的新方法來保存;-) – CrazyDart

+0

@CrazyDart我們可能不應該建議使用新的未經測試的技術。 –

回答

9

隨着BinaryFormatter的

Using fs As New FileStream("DataFile.dat", FileMode.Create) 
    Dim formatter As New BinaryFormatter 
    formatter.Serialize(fs, UserSelection) 
End Using 

和反序列化

Using fs As New FileStream("DataFile.dat", FileMode.Open) 
    Dim formatter As New BinaryFormatter 
    UserSelection = DirectCast(formatter.Deserialize(fs), NameValueCollection) 
End Using 
+0

這個工程,我試過了。 – CrazyDart

+0

+1,謝謝它的作品! – Predator

2

通過對Serializible的魔力,你可以寫一個集合序列化格式,即保存到磁盤,把它在網絡上,無論如何,然後將其反序列化爲一個新的NameValueCollection實例。由於Serializable的寫法,你可以控制它是如何被持久化的。爲了讓它序列化爲XML,你必須編寫(或谷歌)一小段代碼,其中implements IXmlSerializable for a NameValueCollection。序列化到binary開箱即用:

Dim fs as New FileStream("MyNameValueCollection.bin", FileMode.Create) 
Dim bs as New BinaryFormatter() 
bs.Serialize(fs, UserSelection) 
fs.Close() 
+1

這沒有用?作爲OP的相關文檔的鏈接以及XML和二進制的例子都沒有意識到他可以使用除字節數組以外的東西。 – RyanR

+0

+1,你的回答是有幫助:) – Predator

+0

感謝Predator,試圖找出爲什麼有人投票下來 – RyanR

相關問題