1 / 34

Chapter 11

Chapter 11. Data Files. 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.

flynn
Download Presentation

Chapter 11

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11 Data Files

  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.

  3. File Handling Using Streams • Visual Studio handles data files using streams. • A stream is designed to transfer a seriesof 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.

  4. File I/O • Reading and writing data in a disk file • Writing = Output • Reading = Input

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

  6. 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)

  7. Declaring a StreamWriter Object — Examples 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) • The StreamWriter object has both a Write and WriteLine method.

  8. 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

  9. 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)

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

  11. 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 objectand clears the screen

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

  13. 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

  14. 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.

  15. Viewing the Contents of a File (2 of 2)

  16. 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 Closemethod.

  17. 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.

  18. 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

  19. 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( )

  20. 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.

  21. 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.

  22. 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 OpenFileDialogcommon dialog component to display the dialog box. • Then use the object's FileNameproperty to open the selected file.

  23. 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 retrieveFileName property.

  24. Open File to Read Dialog Box Files of Type Determined by Filter Property

  25. 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 (<>).

  26. 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

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

  28. 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.

  29. 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.

  30. 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

  31. 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.

  32. 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.

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

  34. 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.

More Related