Click here to Skip to main content
11,647,170 members (70,238 online)
Click here to Skip to main content

Storing Dataset in a file using Object Serialization

, 26 Aug 2010 CPOL 5.3K 2
Rate this:
Please Sign up or sign in to vote.
in this sample we are storing a dataset object in a binary file using object serializtion , and after serializtion process we will make deserialization to get all inforamtion from tables without connectiing to database

Imports System.Data
Imports System.Data.SqlClient
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Module Module1
    Private connStr As String = "Data Source=.\SQLEXPRESS;Database=Northwind;Integrated Security=True"
    Private _file As String = "C:\ds.dat"
    Sub Main()
        Dim obj As StoringDataSetInFile = New StoringDataSetInFile(connStr, _file)
        Dim employees As List(Of String) = obj.GetDataFromDataSet
        For Each employee As String In employees
    End Sub
End Module
Public Class StoringDataSetInFile
    Private data As DataSet
    Private connStr As String
    Private _file As String
    Sub New(ByVal connStr As String, ByVal _file As String)
        Me.connStr = connStr
        Me._file = _file
    End Sub
    Sub StoreInFile()
        Dim conn As New SqlConnection
        conn.ConnectionString = connStr
            Dim cmd As New SqlCommand
            cmd.Connection = conn
            cmd.CommandText = "Select * From Employees"
            Dim ada As New SqlDataAdapter
            ada.SelectCommand = cmd
            data = New DataSet
            ada.Fill(data, "Employees")
            Dim fs As FileStream = File.Create(Me._file)
            Dim binFormatter As New BinaryFormatter
            binFormatter.Serialize(fs, data)
            binFormatter = Nothing
            data = Nothing
        Catch ex As Exception
            Console.WriteLine("Error :" & ex.ToString)
        End Try
    End Sub
    Sub GetFromFile()
        Dim fs As FileStream = File.Open(Me._file, FileMode.Open)
        Dim binFormatter As New BinaryFormatter
        data = CType(binFormatter.Deserialize(fs), DataSet)
    End Sub
    Function GetDataFromDataSet() As List(Of String)
        Dim dt As New DataTable
        dt = data.Tables("Employees")
        Dim lstFullNames As New List(Of String)
        For Each _row As DataRow In dt.Rows
            Dim str As String = _row("firstname") & " " & _row("lastname")
        Return lstFullNames
    End Function
End Class


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
Jordan Jordan
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150804.2 | Last Updated 26 Aug 2010
Article Copyright 2010 by alrosan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid