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)
obj.StoreInFile()
obj.GetFromFile()
Dim employees As List(Of String) = obj.GetDataFromDataSet
For Each employee As String In employees
Console.WriteLine(employee)
Next
Console.Read()
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
Try
conn.Open()
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")
conn.Close()
Dim fs As FileStream = File.Create(Me._file)
Dim binFormatter As New BinaryFormatter
binFormatter.Serialize(fs, data)
fs.Close()
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)
fs.Close()
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")
lstFullNames.Add(str)
Next
Return lstFullNames
End Function
End Class