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