Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Introduction to Visual Basic.NET Uploaded By: M.Sheraz anjum.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
File Handling Advanced Higher Programming. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a.
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Chapter 6 Multiform Projects Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Chapter 9: Sequential Access Files and Printing
Using Multiple Forms. Creating a New Form ProjectAdd Windows Form.
C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
McGraw-Hill© 2007 The McGraw-Hill Companies, Inc. All rights reserved. 1-1.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
Multiple Forms and Standard Modules
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Using Arrays and File Handling
Chapter 9 Files I/O: Files, Records and Fields Part 3.
5-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 4 I Need a Tour Guide.
Chapter 5 Menus, Common Dialog Boxes, and Methods Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
File I/O 11_file_processing.ppt
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Chapter 10: Structures and Sequential Access Files
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 6 Multiform Projects.
Chapter 10 Sequential Files and Structures. Class 10: Sequential Files Work with different types of sequential files Read sequential files based on the.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
1 Creating Windows GUIs with Visual Studio. 2 Creating the Project New Project Visual C++ Projects Windows Forms Application Give the Project a Name and.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
7-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
6-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Creating Menus Menu Bar – behaves like standard Windows menus Can be used in place of or in addition to buttons to execute a procedure Menu items are controls.
Copyright (c) 2003 by Prentice Hall Provided By: Qasim Al-ajmi Chapter 2 Introduction to Visual Basic Programming Visual Basic.NET.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Creating New Forms Projects can appear more professional when using different windows for different types of information. Select Add Windows Form from.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 6 Looping and Multiple Forms.
Chapter 7 Multiple Forms, Modules, and Menus. Section 7.2 MODULES A module contains code—declarations and procedures—that are used by other files in a.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Visual Basic Fundamental Concepts
Files.
Using Multiple Forms.
Using Procedures and Exception Handling
Sequential Input and Output using Text Files
Visual Basic..
Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline Test-Driving the Microwave Oven Application Designing.
Chapter 3.5 Input and Output
Tonga Institute of Higher Education
CIS16 Application Development and Programming using Visual Basic.net
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill

11-2 Objectives Store and retrieve data in files using streams. Save the values from a list box and reload for the next program run. Check for the end of file. Test whether a file exists. Display the standard Open File and Save File dialog box to allow the user to choose or name the file.

11-3 Simple VB File I/O Supported in Microsoft.VisualBasic.FileIO library Methods: –WriteAllText() –ReadAllText() Example Programs –SimpleDelimitedFileWrite –SimpleDelimitedFileRead

11-4 WriteAllText() Method General Form Examples My.Computer.FileSystem.WriteAllText(FileName, StringToWrite, AppendBoolean) My.Computer.FileSystem.WriteAllText("Names.txt", NameString, True) My.Computer.FileSystem.WriteAllText("C:\FinalCount.txt", CountInteger.ToString(),False)

11-5 ReadAllText() Method General Form Example My.Computer.FileSystem.ReadAllText(FilePath) Try NameString = My.Computer.FileSystem.ReadAllText("Names.txt") Catch MessageBox.Show("File or path not found or invalid") End Try

11-6 Writing & Reading Delimited Files Writing requires concatenating delimiters into the output string: Reading requires a TextFieldParser object: Where you can use the TextFieldType property and the SetDelimiters() method to control the input. My.Computer.FileSystem.WriteAllText("Names.txt", NameTextBox.Text & "," & PhoneTextBox.Text & Environment.NewLine, True) Private NamePhoneTextFieldParser As TextFieldParser

11-7 File Handling Using Streams Visual Studio handles data files 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. Streams are found in the System.IO.namespace. File-handling projects must contain an Imports statement before the statement declaring the form's class.

11-8 File I/O Reading and writing data in a disk file Writing = Output Reading = Input

11-9 Writing Data in a File Using Streams User inputs data into text boxes—the steps for writing data are: 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

11-10 Instantiating a StreamWriter Object General Form Default location for file is where the program executable (.exe) is placed—which is the bin/Debug folder beneath the folder of the current project. Can specify the complete path of the file Can be specified to append data to an existing file – Specify True to append Dim ObjectName As New StreamWriter("FileName") Dim ObjectName As New StreamWriter("FileName", BooleanAppend)

11-11 Declaring a StreamWriter Object — Examples The StreamWriter object has both a Write and WriteLine method. Dim PhoneStreamWriter As New StreamWriter("Phone.txt") Private NamesStreamWriter As New StreamWriter("C:\MyFiles\Names.txt") ' Could throw ' an exception if the path doesn’t exist. Friend LogFileStreamWriter As New StreamWriter("LogFile.txt", True)

11-12 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

11-13 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)

11-14 The WriteLine Method — Examples PhoneStreamWriter.WriteLine(NameTextBox.Text) PhoneStreamWriter.WriteLine(PhoneTextBox.Text) NamesStreamWriter.WriteLine("Sammy") BankBalanceStreamWriter.WriteLine(BalanceDecimal.ToString( ))

11-15 Button Click Event Procedure The user enters data into the text boxes and clicks the Save button, which writes the data from the screen to the StreamWrite object and clears the screen

11-16 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 If the file is not closed, it may remain open for an indefinite time and sometimes may become unusable.

11-17 Closing a File — Example Private Sub ExitButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ExitButton.Click ' Close the form. Me.Close() End Sub

11-18 Viewing the Contents of a File (1 of 2) Text editor, such as Notepad Visual Studio's IDE In the Solution Explorer – Select the Project name. – Click Show All Files button to display the bin folder. – Select the file to display in the editor window.

11-19 Viewing the Contents of a File (2 of 2)

11-20 Reading Data from a File The steps for reading the data from a file are: 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.

11-21 Instantiating a StreamReader Object The file must exist in the specified location where the application expects it or an exception occurs. Declare the StreamReader object in a procedure and enclose it in a Try/Catch block.

11-22 Instantiating a StreamReader Object — Example General Form Example Dim ObjectName As StreamReader ' Inside a procedure. ObjectName = New StreamReader("FileName") Try Dim NamesStreamReader As New StreamReader("C:\MyFiles\Names.txt") Catch MessageBox.Show("File does not exist") End Try

11-23 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. Example NameTextBox.Text = phoneStreamReader.ReadLine( )

11-24 Checking for the End of the File Use StreamReader's. Peek method Peek method 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.

11-25 The File Read Program Reads the file and displays records on a form Each time the user clicks Next, the program reads and displays the next record.

11-26 Using the File Common Dialog Box May allow the user to browse and enter the file name at run time User browses for a folder and filename or enters a new filename. Use the OpenFileDialog common dialog component to display the dialog box. Then use the object's FileName property to open the selected file.

11-27 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.

11-28 Open File to Read Dialog Box Files of Type Determined by Filter Property

11-29 Checking for Successful File Open If the StreamWriter or StreamReader were not instantiated, the file did not open. Use the VB keyword Nothing to check for instantiation. An object that has not been instantiated has a value of Nothing Syntax is important:use the keyword IsNot rather than the not equal operator (<>).

11-30 Using Nothing Keyword ' Is the file already open? If Not PhoneStreamWriter IsNot Nothing Then PhoneStreamWriter.Close( ) End If Must use Keyword Is rather than equal sign

11-31 Checking for Already Open File It’s possible that a user may select the File/Open menu item twice—this causes a problem. A second open file instantiates another file stream- the Close method never executes for the first file. Always check for an active instance of the file stream.

11-32 Using the Save File Dialog Component In addition to the OpenFile Dialog a SaveFileDialog component can be displayed—displays the standard system Save As dialog box. The Save FileDialog allows the user to browse and enter a filename to save. Has most of the same properties as the OpenFileDialog component By default, the SaveFileDialog component checks for an already existing file and displays a dialog box asking the user whether to replace the existing file.

11-33 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.

11-34 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 = FlavorsStreamReader.ReadLine( ) CoffeeComboBox.Items.Add(CoffeeFlavorString) Loop

11-35 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.

11-36 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.

11-37 Querying the User to Save It is a 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.

11-38 The FormClosing Event Procedure FormClosing event procedure is in the 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.