Chapter 3 saving data and objects in files
1 / 27

Chapter 3 Saving Data and Objects In Files - PowerPoint PPT Presentation

  • Uploaded on

Programming In Visual Basic .NET. Chapter 3 Saving Data and Objects In Files. Data Files. To save data from one run of the application to the next Use when there is only a small amount of data that would not warrant the use of a database

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about ' Chapter 3 Saving Data and Objects In Files' - adeola

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 3 saving data and objects in files

Programming In

Visual Basic .NET

Chapter 3Saving Data and Objects In Files

Data files
Data Files

  • To save data from one run of the application to the next

  • Use when there is only a small amount of data that would not warrant the use of a database

  • Use for Windows applications, the default security policy for the Internet and Intranets does not allow access to disk files

Data file terminology
Data File Terminology

  • File ==> Entire collection of data

  • Records ==> Rows, one per entity

  • Fields ==> Columns, data elements within row

Sample data file
Sample Data File

Last Name First Name Phone

Maxwell Harry 909-555-1234

Helm Jennifer 818-555-2222

Colton Craig 909-555-3333



File handling using streams
File Handling Using Streams

  • A Stream is designed to transfer a seriesof bytes from one location to another

  • Streams are objects that have methods and properties

  • Found in the System.IO.namespace

  • File handling projects must contain an Imports statement before the statement declaring the form's class

File i o



Read Input

Write Output



File I/O

  • Reading and writing data in a disk file

    • Writing = Output

    • Reading = Input

Writing data in a file
Writing Data in a File

  • User inputs data into text boxes

  • Declare a new StreamWriterobject

    • Also declares the name of the data file

  • Use StreamWriter's WriteLine method

    • Copies data to a buffer in memory

  • Call StreamWriter's Close method

    • Transfers data from buffer to the file and releases system resources used by the stream

Writing data in a file continued
Writing Data in a File (continued)

  • Declaring a new StreamWriter object opens the file

  • If the file does not exist, a new one is created

  • Declare the StreamWriter object either in the declarations section of your program or in a procedure

Instantiating a streamwriter object
Instantiating a StreamWriter Object

  • General Form

    • Default location for file is the bin directory beneath the folder for the current project

    • Can specify the complete path of the file

Dim ObjectName As New StreamWriter("FileName")

Dim ObjectName As New StreamWriter("FileName", BooleanAppend)

Declaring a streamwriter object examples
Declaring a StreamWriter Object - Examples

Dim phoneStreamWriter As New StreamWriter("Phone.txt")

Dim namesStreamWriter As New StreamWriter("C:\MyFiles\Names.txt")

Dim logFileStreamWriter As New StreamWriter("C:\MyFiles\LogFile.txt", True)

True = Append data to this existing file

Write and writeline methods
Write and WriteLine Methods

  • Write Method

    • Places items consecutively in the file with no delimiter (separator)

  • WriteLine Method

    • Places an enter (carriage return) between items

    • Used in this chapter

The writeline method general form
The WriteLine Method - General Form

  • DataToWrite argument may be string or numeric

  • Converts any numeric data to string and writes string data in the file


The writeline method examples
The WriteLine Method - Examples




bankBalanceStreamWriter.WriteLine(balanceDecimal.ToString( ))

Closing a file
Closing a File

  • Use StreamWriter'sClose method

  • Finishes writing all data from the stream's buffer to the disk and releases system resources

  • Commonly coded in form’s closing event procedure

Closing a file example
Closing a File - Example

Private Sub exitButton_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles exitButton.Click

' Close the file and the form.

phoneStreamWriter.Close( )

Me.Close( )

End Sub

Viewing the contents of a file
Viewing the Contents of a File

  • Text editor, such as Notepad

  • Visual Studio's IDE

    • In the Solution Explorer1. Select the Project name2. Click Show All Files button to display the bin folder3. Select the file to display in the editor window

Viewing the contents of a file continued
Viewing the Contents of a File (continued)

Select project name

Show All Files


Contents of

Data File

New File

bin folder

Reading data from a file
Reading Data from a File

  • Declare an object of the StreamReader class

    • Also declares the name of the data file

    • Opens the file

  • Use StreamReader's ReadLine method

    • May need a loop to retrieve multiple records

  • Call StreamReader's Closemethod

Reading data from a file continued
Reading Data from a File (continued)

  • The file must exist in the specified location or an exception occurs

  • Declare the StreamReader object in a procedure and enclose it in a Try/Catch block

Instantiating a streamreader object
Instantiating a StreamReader Object

  • General Form

  • Example

Dim ObjectName As New StreamReader("FileName")


Dim namesStreamReader As New StreamReader("C:\MyFiles\Names.txt")


MessageBox.Show("File does not exist")

End Try

Using the readline method
Using the ReadLine Method

  • Use to read previously saved data

  • Each time it executes, it reads the next line of data

  • Assign the value from the read to the desired location, such as a label, text box, or string variable

Using the readline method example
Using the ReadLine Method -Example

nameLabel.Text = phoneStreamReader.ReadLine( )

Using the file common dialog box
Using the File Common Dialog Box

  • The previous data file examples included hard-coded file names (and paths)

  • May allow the user to browse and enter the file name at run time

  • Use the OpenFileDialogcommon dialog component to display the dialog box

  • Then use the object's FileNameproperty to open the selected file

Openfiledialog component properties
OpenFileDialog Component Properties

  • Name – Can use default name

  • CheckFileExists

  • CheckPathExists

  • FileName (will be set by user's selection at run time)

  • Filter

  • InitialDirectory (set this property in code)

  • Title

The form closing procedure
The Form_Closing Procedure

  • Form’s Closing event procedure is best location to ask user to save the file

  • Closing event executes before the form closes no matter how user exits program or even Windows


  • Save an object and the current value of all of its properties using Serialization

  • Serialization refers to a series or stream of bits

  • Object's state is converted to a series of bits that can be saved and later used to recreate the object

  • Deserialization is reading the saved data back and recreating the object

Serialization continued
Serialization (continued)

  • To save an object

    • Class must be declared as Serializable

    • Must have a Formatter

  • Two types of Formatters

    • Binary, stores data in a binary form

    • SOAP(Simple Object Access Protocol), stores data in an XML format