My.Settings does not save an ArrayList

若如初见. 提交于 2019-11-29 16:10:30

If you have the data in an arrayList (or List or Collection), and you are looking at the BinaryFormatter for the workaround, there is no good reason to also also use My.Settings. You can do what it does thru the BinaryFormatter, which is just saving the file and picking a name.

Imports System.Runtime.Serialization.Formatters.Binary

Private MRUArrayList = New ArrayList
' file location
 myFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment. _
                    SpecialFolder.ApplicationData),
                                    CompName,
                                    ProgramName,
                                    File)

Save Settings:

Dim bf As New BinaryFormatter
Using fs As New FileStream(myFile, FileMode.OpenOrCreate)
    bf.Serialize(fs, MRUArrayList )
End Using

Load Settings:

' dont attempt for the first time run
If File.Exists(myFile) = False Then Return False

Dim bf As New BinaryFormatter
Using fs As New FileStream(myFile, FileMode.Open)
    MRUArrayList = CType(bf.Deserialize(fs), ArrayList)
End Using

Once you have to resort to BF for the workaround, replacing the Memory Stream with a File Stream gets rid of the need for My.Settings entirely, lets you store the file wherever you want and it wont change by version, user changing the EXE name or anything else unless you change the file name formula above.

For an App with more than just the MRU ArrayList, you can use a Class in its place to store all the settings to the location you want very much like Settings does. You just need to tag the Class as <Serializable>. It remains one line of code to save the entire class, one line to reconstitute it. There are some limitations, but they are not difficult to overcome.

Private myNewSettings As New myNewSettingsClass
...

bf.Serialize(fs, myNewSettings)

myNewSettings = CType(bf.Deserialize(fs), myNewSettingsClass )

In other situations, you can use the XML serializer or ProtoBuf-NET as needed for the situation.

You can also have your new settings automatically saved when the program exits: Go to Project Properties --> Application --> Click View Application Events. Select "Application Events" from the left menu, and ShutDown from the right event menu.

Private Sub MyApplication_Shutdown(sender As Object, 
          e As EventArgs) Handles Me.Shutdown

   ' add your code to Save (above) here
End Sub

Likewise you can have it automatically load them in the Startup event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!