某些数据类型不会保存在My.Settings中

时间:2016-05-22 19:18:01

标签: vb.net visual-studio-2015 application-settings

我在将自定义对象System.ObjectMicrosoft.VisualBasic.Collection保存到My.Settings时遇到问题。这些是下拉菜单中未列出的所有对象或通过点击浏览。任何其他预定义的对象都很有用。

2 个答案:

答案 0 :(得分:1)

我最终序列化以解决我的问题。我将对象转换为字节数组,然后将字节数组转换为字符串。如果要拉动设置,只需反转即可。请记住将类标记为Serializable。

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

Module SettingsSerialization
    Public Function ObjectToByteArray(ByVal Obj As Object) As Byte()
        Dim bf As BinaryFormatter = New BinaryFormatter()
        Using ms As MemoryStream = New MemoryStream()
            bf.Serialize(ms, Obj)
            Return ms.ToArray()
        End Using
    End Function

Public Function ByteArrayToString(ByVal ByteArray As Byte()) As String
    Return Convert.ToBase64String(ByteArray)
End Function

Public Function StringToByteArray(ByVal Str As String) As Byte()
    Return Convert.FromBase64String(Str)
End Function

Public Function ByteArrayToObject(ByVal ByteArray As Byte()) As Object
        Dim bf As BinaryFormatter = New BinaryFormatter
        Using ms As MemoryStream = New MemoryStream
            ms.Write(ByteArray, 0, ByteArray.Length)
            ms.Seek(0, SeekOrigin.Begin)
            Return bf.Deserialize(ms)
        End Using
    End Function
End Module

使用示例:

'Getting the setting.
Dim myclass As CustomClass = SettingsSerialization.ByteArrayToObject(SettingsSerialization.StringToByteArray(My.Settings.CustomClass))

'Properly setting and saving.
My.Settings.CustomClass = SettingsSerialization.ByteArrayToString(SettingsSerialization.ObjectToByteArray(CustomClass))
My.Settings.Save() 

答案 1 :(得分:1)

I'd like to be able to pass any object, otherwise I have to overload the functions.

泛型意味着永远不必打包As Object

Private Function SerializeToB64(Of T)(item As T) As String

    Using ms As New MemoryStream
        Dim bf As New BinaryFormatter
        bf.Serialize(ms, item)
        Return Convert.ToBase64String(ms.ToArray())
    End Using
End Function

Private Function DeSerializeFromB64(Of T)(data As String) As T

    Using ms As New MemoryStream(Convert.FromBase64String(data))
        Dim bf As New BinaryFormatter
        ' serializer creates the new object
        Dim newT As T = CType(bf.Deserialize(ms), T)
        Return newT
    End Using

End Function

用法:

Dim A As New Animal With {.Name = "Gizmo", .Species = "Mugwai"}

Dim b64 = SerializeToB64(A)

Dim A2 = DeSerializeFromB64(Of Animal)(b64)
Console.WriteLine("Animal name: {0}, species: {1}", A2.Name, A2.Species)

如果要保存多个对象,可以创建一个“Mailer”来保存所有对象,并将它们全部序列化:

<Serializable>
Public Class SerializingMailer
    Public Property AnimalItem As Animal
    Public Property FooItem As Foo
    Public Property BarItem As Bar

    ' some serializers require a simple ctor
    Public Sub New()

    End Sub
End Class

请注意,不是将B64字符串反馈给My.Settings,而是使用FileStream将它们自己保存到磁盘。