Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Saving Data and Objects In Files

Similar presentations


Presentation on theme: "Chapter 11 Saving Data and Objects In Files"— Presentation transcript:

1 Chapter 11 Saving Data and Objects In Files
Programming In Visual Basic .NET

2 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

3 Data File Terminology File ==> Entire collection of data
Records ==> Rows, one per entity Fields ==> Columns, data elements within row © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

4 Sample Data File Records Fields Last Name First Name Phone
Maxwell Harry Helm Jennifer Colton Craig Records Fields © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

5 File Handling Using Streams
A Stream is designed to transfer a series of 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

6 File I/O Reading and writing data in a disk file Writing = Output
Reading = Input Write Output Read Input Form Data File © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

7 Writing Data in a File User inputs data into text boxes
Declare a new StreamWriter object 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

8 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

9 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) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

10 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

11 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

12 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 ObjectName.WriteLine(DataToWrite) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

13 The WriteLine Method - Examples
phoneStreamWriter.WriteLine(nameTextBox.Text) phoneStreamWriter.WriteLine(phoneTextBox.Text) namesStreamWriter.WriteLine("Sammy") bankBalanceStreamWriter.WriteLine(balanceDecimal.ToString( )) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

14 Closing a File Use StreamWriter's Close 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

15 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

16 Viewing the Contents of a File
Text editor, such as Notepad Visual Studio's IDE In the Solution Explorer 1. Select the Project name 2. Click Show All Files button to display the bin folder 3. Select the file to display in the editor window © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

17 Viewing the Contents of a File (continued)
Select project name Show All Files button Contents of Data File bin folder New File © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

18 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 Close method © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

19 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

20 Instantiating a StreamReader Object
General Form Example Dim ObjectName As New StreamReader("FileName") Try Dim namesStreamReader As New StreamReader("C:\MyFiles\Names.txt") Catch MessageBox.Show("File does not exist") End Try © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

21 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

22 Using the ReadLine Method -Example
nameLabel.Text = phoneStreamReader.ReadLine( ) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

23 Checking for the End of the File
Use StreamReader's Peek method Peek looks at the next element without reading it If you Peek beyond the last element the value returned is negative 1 (-1) Code an If statement to execute Peek and compare for <> -1 before reading Read elements in the exact same order as they were written to obtain valid data © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

24 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 OpenFileDialog common dialog component to display the dialog box Then use the object's FileName property to open the selected file © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

25 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

26 Displaying the Open File Dialog Box
Add OpenFileDialog component to form At design time set initial properties for Name, CheckFileExists, CheckPathExists, Filter and Title In code set InitialDirectory property to Application.StartUpPath Display dialog box using ShowDialog method and retrieve FileName property © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

27 Open File to Read Dialog Box
Files of Type Determined by Filter Property © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

28 Open File to Read Dialog Box - Code Example
Private Sub fileOpenMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles fileOpenMenuItem.Click ' Open the file. Dim responseDialogResult As DialogResult ' Begin in the project folder. OpenDialog1.InitialDirectory = Application.StartupPath ' Display the File Open dialog box. responseDialogResult = OpenDialog1.ShowDialog( ) ' Make sure that the user didn’t click the Cancel button. If responseDialogResult <> DialogResult.Cancel Then ' Open the output file. phoneStreamWriter = New StreamWriter(OpenDialog1.FileName) End If End Sub © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

29 Checking for Successful File Open
If the StreamWriter or StreamReader were not instantiated, the file did not open Use the Nothing keyword to check for instantiation An object that has not been instantiated has a value of Nothing © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

30 Using Nothing Keyword ' Is the file already open?
If Not phoneStreamWriter Is Nothing Then phoneStreamWriter.Close( ) End If Must use Keyword Is rather than equal sign © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

31 Saving the Contents of a List Box
Do not assign values at design time, when program begins, open data file and read items into Items collection of List Box If user makes changes to list, ask whether to save list when program ends, include a menu option to save list If file of list elements does not exist when program begins, allow user to create new list by adding items © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

32 Loading the List Box Read the file into the list in Form_Load
Loop through the file until all elements are read Use the Items.Add method to add the data elements to the list Dim coffeeFlavor As String ' Read all elements into the list. Do Until flavorsStreamReader.Peek = -1 coffeeFlavorString = flavorStreamReader.ReadLine( ) coffeeComboBox.Items.Add(coffeeFlavorString) Loop © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

33 Checking for Existence of the File
When the StreamReader object is created, the constructor makes sure the file exists If it does not exist, give the user options Try to locate the data file again Exit the program Begin with an empty list, add items, and create a new file © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

34 Saving the File Provide a menu option for the user to save the file
Open a StreamWriter object Loop through the Items collection of the list box, saving each element with a WriteLine method © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

35 Saving the File - Example
Private Sub fileSaveMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles fileSaveMenuItem.Click ' Save the list box contents in a file. Dim indexInteger As Integer Dim numberItemsInteger As Integer ' Open the file. Dim flavorsStreamWriter As New StreamWriter("Coffees.txt") ' Save the items in the file. numberItemsInteger = coffeeComboBox.Items.Count - 1 For indexInteger = 0 To numberItemsInteger flavorsStreamWriter.WriteLine(coffeeComboBox.Items(indexInteger)) Next indexInteger flavorsStreamWriter.Close( ) ' Close the file. isDirtyBoolean = False ' Reset changed status. End Sub © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

36 Querying the User to Save
Good idea to ask users if they want to save any changes made before program ends Use a module-level Boolean variable, isDirtyBoolean, to keep track of changes In procedures that allow changes, set variable to True After saving file set variable to False © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

37 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

38 Serialization 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

39 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 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

40 Serialization (continued)
Make any class module serializable allowing public properties of an object to be saved Declare the class as Serializable Declare a Formatter object Declare a FileStream object that includes the name of the file Use the Formatter object's Serialize method to save the object's properties Close the FileStream © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

41 Making a Class Serializable
Modify the class header to include the Serializable attribute Add < Serializable ( ) > in front of the class header Example < Serializable ( ) > Public Class BookSale ' Body of the class. End Class © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

42 Adding a Formatter Object
Write the code to store (serialize) the object in your form's code, not in the serialize class Declare a new formatter object using either BinaryFormatter class SoapFormatter class A formatter object requires an Imports statement for the formatter class © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

43 Adding a Formatter Object – Code Example
Imports System.IO Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary Dim FormatObject As SoapFormatter = New SoapFormatter Dim FormatObject As BinaryFormatter = New BinaryFormatter © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

44 Using a FileStream Serialization uses the FileStream class rather than StreamReader and StreamWriter classes Declare a FileStream including Name and Path for file File Mode Create ==> Open the file for output Open ==> Retrieve the file OpenOrCreate (module level, read and write) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

45 Declaring a FileStream Object
Constructor Example Dim ObjectName As FileStream = New FileStream("file name", _ FileMode.Open|Create) Dim booksFileStream As FileStream = New FileStream _ ("Books.txt", FileMode.Create) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

46 Saving an Object Use the Serialize method of the Formatter to save an object Serialize method writes data to buffer Include Close method to complete the save operation to disk © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

47 Serialize Method General Form Example
FormatterObject.Serialize(StreamObject, ObjectToSave) bookBinaryFormatter.Serialize(booksFileStream, aBookSale) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

48 Recreating an Object Read an object back in with the Deserialize method of the formatter Create a FileStream object in the Open mode Declare a Formatter object Use the Formatter's Deserialize method, converting the input to the desired type Transfer fields from the object to the screen Close the stream Convert input data to correct type © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Download ppt "Chapter 11 Saving Data and Objects In Files"

Similar presentations


Ads by Google