如何将System.Collections.Specialized.NameValueCollection实例保存到硬盘并将其作为实例加载回来?

时间:2011-06-24 20:33:52

标签: .net vb.net visual-studio-2010

我有以下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")

我需要将此实例保存到硬盘,然后将其作为实例从硬盘加载回来。我该怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()