serializing data to a file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • PJ6

    #1

    serializing data to a file

    OK I haven't ever done this before... I'm going to need to create "project"
    files to which my application can save and retreive data. Rather than
    worrying about the details fo the format too much, I'd like to just have
    everything saved as a serialized collection so whatever I chose to store in
    a file can be kind of arbitrary. I thought I'd use the .resx model VS uses
    for storing forms information, but the resource manager does no allow
    writing and anyhow I'm not sure this is the best way to do it. Can anyone
    point me to so good examples on how best to approach this?

    TIA,
    Paul


  • Michael Bosch

    #2
    Re: serializing data to a file

    Hi Paul,

    This is typically fairly simple to do. You can mark your classes with the
    <Serializable ()> attribute. Then just use an XMLSerializer to write to and
    load from a file. What version of the framework are you using? If you're
    on 2.0, you can use generics to encapsulate this kind of functionality.. .
    Here's a class I created to facilitate this.

    Regards,

    Michael Bosch

    Namespace Utilities

    ''' <summary>
    ''' Provides a generic way to create an XML file from
    ''' any class that is serializable.
    ''' </summary>
    ''' <typeparam name="t">The type of class you wish to create an XML file
    from.</typeparam>
    ''' <remarks></remarks>
    ''' <example>
    ''' <code>
    ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)
    '''
    ''' With doc
    ''' .Value.FirstNam e = "Mike"
    ''' .Value.LastName = "Bosch"
    ''' .Save("C:\custo mer.xml")
    ''' End With
    ''' </code>
    ''' Or alternatively using a predefined value:
    ''' <code>
    ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)(obj)
    ''' doc.Save("C:\cu stomer.xml")
    ''' </code>
    ''' </example>
    '''

    <Serializable() > _
    Public Class PersistableDocu ment(Of t As New)

    Private mValue As New t

    Public Property Value() As t
    Get
    Return mValue
    End Get
    Set(ByVal value As t)
    mValue = value
    End Set
    End Property

    Public Sub Save(ByVal fileName As String)

    Using fs As New IO.FileStream(f ileName, IO.FileMode.Cre ate)
    Dim xser As New
    System.Xml.Seri alization.XmlSe rializer(GetTyp e(t))
    xser.Serialize( fs, mValue)
    End Using

    End Sub

    Public Sub Load(ByVal fileName As String)

    Using fs As New IO.FileStream(f ileName, IO.FileMode.Ope n)
    Dim xser As New Xml.Serializati on.XmlSerialize r(GetType(t))
    mValue = DirectCast(xser .Deserialize(fs ), t)
    End Using

    End Sub

    Public Sub New(ByVal value As t)
    Me.mValue = value
    End Sub

    Public Sub New()

    End Sub
    End Class

    End Namespace
    "PJ6" <noone@nowhere. net> wrote in message
    news:%23vrHSyed GHA.1656@TK2MSF TNGP02.phx.gbl. ..[color=blue]
    > OK I haven't ever done this before... I'm going to need to create
    > "project" files to which my application can save and retreive data. Rather
    > than worrying about the details fo the format too much, I'd like to just
    > have everything saved as a serialized collection so whatever I chose to
    > store in a file can be kind of arbitrary. I thought I'd use the .resx
    > model VS uses for storing forms information, but the resource manager does
    > no allow writing and anyhow I'm not sure this is the best way to do it.
    > Can anyone point me to so good examples on how best to approach this?
    >
    > TIA,
    > Paul
    >[/color]


    Comment

    • PJ6

      #3
      Re: serializing data to a file

      Nice!

      Thanks :)

      Paul

      "Michael Bosch" <dotnetmichael@ gmail.com> wrote in message
      news:m459g.2110 7$Sl4.17336@big news1.bellsouth .net...[color=blue]
      > Hi Paul,
      >
      > This is typically fairly simple to do. You can mark your classes with the
      > <Serializable ()> attribute. Then just use an XMLSerializer to write to
      > and load from a file. What version of the framework are you using? If
      > you're on 2.0, you can use generics to encapsulate this kind of
      > functionality.. . Here's a class I created to facilitate this.
      >
      > Regards,
      >
      > Michael Bosch
      >
      > Namespace Utilities
      >
      > ''' <summary>
      > ''' Provides a generic way to create an XML file from
      > ''' any class that is serializable.
      > ''' </summary>
      > ''' <typeparam name="t">The type of class you wish to create an XML
      > file from.</typeparam>
      > ''' <remarks></remarks>
      > ''' <example>
      > ''' <code>
      > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)
      > '''
      > ''' With doc
      > ''' .Value.FirstNam e = "Mike"
      > ''' .Value.LastName = "Bosch"
      > ''' .Save("C:\custo mer.xml")
      > ''' End With
      > ''' </code>
      > ''' Or alternatively using a predefined value:
      > ''' <code>
      > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)(obj)
      > ''' doc.Save("C:\cu stomer.xml")
      > ''' </code>
      > ''' </example>
      > '''
      >
      > <Serializable() > _
      > Public Class PersistableDocu ment(Of t As New)
      >
      > Private mValue As New t
      >
      > Public Property Value() As t
      > Get
      > Return mValue
      > End Get
      > Set(ByVal value As t)
      > mValue = value
      > End Set
      > End Property
      >
      > Public Sub Save(ByVal fileName As String)
      >
      > Using fs As New IO.FileStream(f ileName, IO.FileMode.Cre ate)
      > Dim xser As New
      > System.Xml.Seri alization.XmlSe rializer(GetTyp e(t))
      > xser.Serialize( fs, mValue)
      > End Using
      >
      > End Sub
      >
      > Public Sub Load(ByVal fileName As String)
      >
      > Using fs As New IO.FileStream(f ileName, IO.FileMode.Ope n)
      > Dim xser As New Xml.Serializati on.XmlSerialize r(GetType(t))
      > mValue = DirectCast(xser .Deserialize(fs ), t)
      > End Using
      >
      > End Sub
      >
      > Public Sub New(ByVal value As t)
      > Me.mValue = value
      > End Sub
      >
      > Public Sub New()
      >
      > End Sub
      > End Class
      >
      > End Namespace
      > "PJ6" <noone@nowhere. net> wrote in message
      > news:%23vrHSyed GHA.1656@TK2MSF TNGP02.phx.gbl. ..[color=green]
      >> OK I haven't ever done this before... I'm going to need to create
      >> "project" files to which my application can save and retreive data.
      >> Rather than worrying about the details fo the format too much, I'd like
      >> to just have everything saved as a serialized collection so whatever I
      >> chose to store in a file can be kind of arbitrary. I thought I'd use the
      >> .resx model VS uses for storing forms information, but the resource
      >> manager does no allow writing and anyhow I'm not sure this is the best
      >> way to do it. Can anyone point me to so good examples on how best to
      >> approach this?
      >>
      >> TIA,
      >> Paul
      >>[/color]
      >
      >[/color]


      Comment

      • Dennis

        #4
        Re: serializing data to a file

        You can also serialize a class to a binary file;

        Imports System.Runtime. Serialization.F ormatters.Binar y
        Imports System.Runtime. Serialization

        Sub Main
        dim InitSet as New InitSettings
        'Set properties you want in InitSet
        SerializeSettin gs(InitSet, "MySettingsFile Name") ' Serializes settings
        to a file
        InitSet = DeSerializeSett ings("MySetting sFileName") 'Deserializes from
        file
        End Sub

        <Serializable() > Public Class InitSettings
        Public MainWindowState As FormWindowState = FormWindowState .Maximized
        Public DataBaseFileNam e As String = ApplicationData Path & "D&ERecipes.mdb "
        Public LastBackUpFileN ame As String
        Public LastMusicSource As Integer
        Public LastFileSourceP ath As String = "c:\"
        Public AudioDisplayInd ex As AudioDisplay = AudioDisplay.Av gBitRate
        Public DateDisplayInde x As DateDisplay = DateDisplay.Yea rRecorded
        End Class

        Public Function SerializeSettin gs(InitSet as InitSettings, SettingsFileNam e
        as String) As Boolean
        Dim s As New MemoryStream
        Dim formatter As New BinaryFormatter
        Dim rs As New FileStream(Sett ingsFileName, FileMode.OpenOr Create)
        Try
        formatter.Seria lize(s, InitSet)
        s.WriteTo(rs)
        Catch
        Return False
        Finally
        s = Nothing
        formatter = Nothing
        rs.Close()
        rs = Nothing
        End Try
        Return True
        End Function
        Private Function DeSerializeSett ings(SettingsFi leName as String) As
        InitSettings
        Dim ms As FileStream
        Dim formatter As New BinaryFormatter
        Try
        ms = New FileStream(Sett ingsFileName, FileMode.Open)
        ms.Seek(0, SeekOrigin.Begi n)
        Return DirectCast(form atter.Deseriali ze(ms), InitSettings)
        Catch
        Return nothing
        Finally
        ms.Close()
        formatter = Nothing
        End Try
        End Function
        --
        Dennis in Houston


        "PJ6" wrote:
        [color=blue]
        > Nice!
        >
        > Thanks :)
        >
        > Paul
        >
        > "Michael Bosch" <dotnetmichael@ gmail.com> wrote in message
        > news:m459g.2110 7$Sl4.17336@big news1.bellsouth .net...[color=green]
        > > Hi Paul,
        > >
        > > This is typically fairly simple to do. You can mark your classes with the
        > > <Serializable ()> attribute. Then just use an XMLSerializer to write to
        > > and load from a file. What version of the framework are you using? If
        > > you're on 2.0, you can use generics to encapsulate this kind of
        > > functionality.. . Here's a class I created to facilitate this.
        > >
        > > Regards,
        > >
        > > Michael Bosch
        > >
        > > Namespace Utilities
        > >
        > > ''' <summary>
        > > ''' Provides a generic way to create an XML file from
        > > ''' any class that is serializable.
        > > ''' </summary>
        > > ''' <typeparam name="t">The type of class you wish to create an XML
        > > file from.</typeparam>
        > > ''' <remarks></remarks>
        > > ''' <example>
        > > ''' <code>
        > > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)
        > > '''
        > > ''' With doc
        > > ''' .Value.FirstNam e = "Mike"
        > > ''' .Value.LastName = "Bosch"
        > > ''' .Save("C:\custo mer.xml")
        > > ''' End With
        > > ''' </code>
        > > ''' Or alternatively using a predefined value:
        > > ''' <code>
        > > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)(obj)
        > > ''' doc.Save("C:\cu stomer.xml")
        > > ''' </code>
        > > ''' </example>
        > > '''
        > >
        > > <Serializable() > _
        > > Public Class PersistableDocu ment(Of t As New)
        > >
        > > Private mValue As New t
        > >
        > > Public Property Value() As t
        > > Get
        > > Return mValue
        > > End Get
        > > Set(ByVal value As t)
        > > mValue = value
        > > End Set
        > > End Property
        > >
        > > Public Sub Save(ByVal fileName As String)
        > >
        > > Using fs As New IO.FileStream(f ileName, IO.FileMode.Cre ate)
        > > Dim xser As New
        > > System.Xml.Seri alization.XmlSe rializer(GetTyp e(t))
        > > xser.Serialize( fs, mValue)
        > > End Using
        > >
        > > End Sub
        > >
        > > Public Sub Load(ByVal fileName As String)
        > >
        > > Using fs As New IO.FileStream(f ileName, IO.FileMode.Ope n)
        > > Dim xser As New Xml.Serializati on.XmlSerialize r(GetType(t))
        > > mValue = DirectCast(xser .Deserialize(fs ), t)
        > > End Using
        > >
        > > End Sub
        > >
        > > Public Sub New(ByVal value As t)
        > > Me.mValue = value
        > > End Sub
        > >
        > > Public Sub New()
        > >
        > > End Sub
        > > End Class
        > >
        > > End Namespace
        > > "PJ6" <noone@nowhere. net> wrote in message
        > > news:%23vrHSyed GHA.1656@TK2MSF TNGP02.phx.gbl. ..[color=darkred]
        > >> OK I haven't ever done this before... I'm going to need to create
        > >> "project" files to which my application can save and retreive data.
        > >> Rather than worrying about the details fo the format too much, I'd like
        > >> to just have everything saved as a serialized collection so whatever I
        > >> chose to store in a file can be kind of arbitrary. I thought I'd use the
        > >> .resx model VS uses for storing forms information, but the resource
        > >> manager does no allow writing and anyhow I'm not sure this is the best
        > >> way to do it. Can anyone point me to so good examples on how best to
        > >> approach this?
        > >>
        > >> TIA,
        > >> Paul
        > >>[/color]
        > >
        > >[/color]
        >
        >
        >[/color]

        Comment

        • PJ6

          #5
          Re: serializing data to a file

          After the objects are loaded, I want to give the user the ability to delete
          the entire "project", which is in effect the save file's partening folder.
          Only, when I load items using this deserializer, I get an error complaining
          that the process cannot access the file because it is in use by another
          process. This is strange considering "using" is supposed to explcitly
          dispose the file stream after the block has completed execution. Manually
          disposing the file stream doesn't help. Any ideas?

          Thanks,
          Paul

          "Michael Bosch" <dotnetmichael@ gmail.com> wrote in message
          news:m459g.2110 7$Sl4.17336@big news1.bellsouth .net...[color=blue]
          > Hi Paul,
          >
          > This is typically fairly simple to do. You can mark your classes with the
          > <Serializable ()> attribute. Then just use an XMLSerializer to write to
          > and load from a file. What version of the framework are you using? If
          > you're on 2.0, you can use generics to encapsulate this kind of
          > functionality.. . Here's a class I created to facilitate this.
          >
          > Regards,
          >
          > Michael Bosch
          >
          > Namespace Utilities
          >
          > ''' <summary>
          > ''' Provides a generic way to create an XML file from
          > ''' any class that is serializable.
          > ''' </summary>
          > ''' <typeparam name="t">The type of class you wish to create an XML
          > file from.</typeparam>
          > ''' <remarks></remarks>
          > ''' <example>
          > ''' <code>
          > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)
          > '''
          > ''' With doc
          > ''' .Value.FirstNam e = "Mike"
          > ''' .Value.LastName = "Bosch"
          > ''' .Save("C:\custo mer.xml")
          > ''' End With
          > ''' </code>
          > ''' Or alternatively using a predefined value:
          > ''' <code>
          > ''' Dim doc As New Utilities.Persi stableDocument( Of Customer)(obj)
          > ''' doc.Save("C:\cu stomer.xml")
          > ''' </code>
          > ''' </example>
          > '''
          >
          > <Serializable() > _
          > Public Class PersistableDocu ment(Of t As New)
          >
          > Private mValue As New t
          >
          > Public Property Value() As t
          > Get
          > Return mValue
          > End Get
          > Set(ByVal value As t)
          > mValue = value
          > End Set
          > End Property
          >
          > Public Sub Save(ByVal fileName As String)
          >
          > Using fs As New IO.FileStream(f ileName, IO.FileMode.Cre ate)
          > Dim xser As New
          > System.Xml.Seri alization.XmlSe rializer(GetTyp e(t))
          > xser.Serialize( fs, mValue)
          > End Using
          >
          > End Sub
          >
          > Public Sub Load(ByVal fileName As String)
          >
          > Using fs As New IO.FileStream(f ileName, IO.FileMode.Ope n)
          > Dim xser As New Xml.Serializati on.XmlSerialize r(GetType(t))
          > mValue = DirectCast(xser .Deserialize(fs ), t)
          > End Using
          >
          > End Sub
          >
          > Public Sub New(ByVal value As t)
          > Me.mValue = value
          > End Sub
          >
          > Public Sub New()
          >
          > End Sub
          > End Class
          >
          > End Namespace
          > "PJ6" <noone@nowhere. net> wrote in message
          > news:%23vrHSyed GHA.1656@TK2MSF TNGP02.phx.gbl. ..[color=green]
          >> OK I haven't ever done this before... I'm going to need to create
          >> "project" files to which my application can save and retreive data.
          >> Rather than worrying about the details fo the format too much, I'd like
          >> to just have everything saved as a serialized collection so whatever I
          >> chose to store in a file can be kind of arbitrary. I thought I'd use the
          >> .resx model VS uses for storing forms information, but the resource
          >> manager does no allow writing and anyhow I'm not sure this is the best
          >> way to do it. Can anyone point me to so good examples on how best to
          >> approach this?
          >>
          >> TIA,
          >> Paul
          >>[/color]
          >
          >[/color]


          Comment

          Working...