How to save a listof to disk

R

roidy

I have the following code:-

<Serializable()> Structure TestStruct
Dim test1 As String
Dim test2 As String
Dim test3 As Interger
End Structure

Public TestList As New List(Of TestStruct)

I then add a bunch of items to the list, my question is how do I save the
entire List to a disk file? I have no problem writing a single TestStruct
using serialization, but can`t figure out how to write the entire List. It
seems you can`t serialize a List.

Rob
 
R

roidy

Ok so I solved the problem by adding the list to a dummy structure and then
serializing that.

<Serializable()> Structure TestStruct
Dim test1 As String
Dim test2 As String
Dim test3 As Interger
End Structure

<Serializable()> Structure Dummy
Public TestList As New List(Of TestStruct)
End Structure

Now I can just use

Dim BF As New
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim MS As New System.IO.MemoryStream()

BF.Serialize(MS, Dummy)
My.Computer.FileSystem.WriteAllBytes("test.dat", MS.GetBuffer(), False)

Probably not the best solution but at least it works.

Rob
 
F

Family Tree Mike

roidy said:
I have the following code:-

<Serializable()> Structure TestStruct
Dim test1 As String
Dim test2 As String
Dim test3 As Interger
End Structure

Public TestList As New List(Of TestStruct)

I then add a bunch of items to the list, my question is how do I save
the entire List to a disk file? I have no problem writing a single
TestStruct using serialization, but can`t figure out how to write the
entire List. It seems you can`t serialize a List.

Rob

Like this:

Sub Main()
Dim lots As New List(Of TestStruct)
lots.Add(New TestStruct())
lots.Add(New TestStruct())

Using fs As New FileStream("c:\test\test.xml", _
FileMode.Create, FileAccess.Write)

Dim xs As New XmlSerializer(lots.GetType)
Dim xw As New XmlTextWriter(fs, Encoding.UTF8)
xs.Serialize(xw, lots)
End Using
End Sub
 
R

roidy

Thanks Mike, but I don't really want to write it out as a xml text file as
the actual structures I`m using contain lots of binary data eg multiply
image files. The example I gave was just to illustrate the point. The
method I`m using at the moment seems to be working fine. It just means I`ve
got to encapsulate my list in another structure.

<Serializable()> Structure TestStruct
Dim test1 As String
Dim test2 As String
Dim test3 As Interger
End Structure

<Serializable()> Structure Dummy
Public TestList As New List(Of TestStruct)
End Structure

Dim BF As New _
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim MS As New System.IO.MemoryStream()

BF.Serialize(MS, Dummy)
My.Computer.FileSystem.WriteAllBytes("test.dat", MS.GetBuffer(), False)


Thanks
Rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top