In a contact manager program I've been storing data in CSV files for each contact and would like a way to compress this data into a single file.
I have attempted using data entry tools in the visual studio toolbox and template class, though I have never quite figured out how to use them. What would be especially convenient is if I could somehow store a generic class instance as opposed to having to c开发者_如何学Come up with a string representation of it, and then parse it.
I'd also need to figure out how to tell the program what to do when a file is opened (I've noticed in the properties how to associate a file type with the program though am not sure how to tell it what to do when it's opened).
IMHO, switch to sqlite. You'll be able to query faster, compress it, and much more then working with a csv file.
Found this article about Serialization and it works very well!
http://www.vbdotnetheaven.com/UploadFile/Nimusoft/Serialization105022008052559AM/Serialization1.aspx
edit: Figured I should probably post more. I have a class IOwner, and list of this class contains all of my database. So I added serialization tags to this class and others it references then substitute in those properties with the ones shown on the article:
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Namespace BinarySerialization
<Serializable()> _
Public Class IFile
Implements ISerializable
Public Contacts As List(Of IOwner)
Public Self As IOwner
Public Cars As List(Of Vehicle)
Public path As String
Public Sub New()
End Sub
Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
Data.Self = info.GetValue("Self", GetType(IOwner))
Data.Contacts = info.GetValue("Contacts", GetType(List(Of IOwner)))
Data.Cars = info.GetValue("Cars", GetType(List(Of Vehicle)))
End Sub
Public Sub WriteFile()
Dim s As New FileStream(path, FileMode.Create, FileAccess.ReadWrite)
Dim B As New BinaryFormatter()
B.Serialize(s, Me)
s.Close()
End Sub
Public Function ReadFile() As IFile
Dim Fs As New FileStream(path, FileMode.Open, FileAccess.Read)
Dim F As New BinaryFormatter()
Dim s1 As IFile = DirectCast(F.Deserialize(Fs), IFile)
Fs.Close()
Return s1
End Function
#Region "ISerializable Members"
Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) Implements ISerializable.GetObjectData
info.AddValue("Self", Data.Self)
info.AddValue("Contacts", Data.Contacts)
info.AddValue("Cars", Data.Cars)
End Sub
#End Region
End Class
End Namespace
UPDATE 2016
Binary serialization is not advisable for complex structures that are subject to change. Using a database storage method such as SQLite
and using an ODB (object database model) would have been preferable.
精彩评论