Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Visual Basic .NET Coach

Similar presentations


Presentation on theme: "The Visual Basic .NET Coach"— Presentation transcript:

1 The Visual Basic .NET Coach
Chapter 9 – Files A simple way to store data so that it is accessible the next time you wish to execute the application is to store it in a data file. There are three types of data files: binary, sequential and random access. The Visual Basic .NET Coach

2 The Visual Basic .NET Coach
Chapter 9 – Files 9.1 Sequential Files A sequential file allows reading or writing the file from the beginning of the file until the end of the file. Files that are read and written sequentially are plain text files commonly known as ASCII files. ASCII stands for American Standard Code for Information Interchange. You can view or edit small ASCII files using the Notepad application that comes with Windows, or you can use a word processor and then select the ASCII option when you save the file. The Visual Basic .NET Coach

3 The Visual Basic .NET Coach
Chapter 9 – Files If you wanted to save the information in your Student Search application a sequential file of this information might look like one of the following two files: 1 Salvage Jeff Computer Science Senior 2 Cunningham John Basket Weaving Freshman 1.0 3 Pepito Suzanne Industrial Engineering Junior 4 Burke Tim MIS Senior 5 Fletcher Irwin Film Senior 1, "Salvage", "Jeff", "Computer Science", "Senior", 4.0 2, "Cunningham", "John", "Basket Weaving", "Freshman", 1.0 3, "Pepito", "Suzanne", "Industrial Engineering", "Junior", 3.8 4, "Burke" ,"Tim", "MIS", "Senior", 3.92 5, "Fletcher", "Irwin", "Film", "Senior", 3.99 The Visual Basic .NET Coach

4 The Visual Basic .NET Coach
Chapter 9 – Files A fixed-width file contains information formatted so that each line stores each data item in a fixed location within the line. The comma-delimited file stores each data item with a comma separating each item. A comma-delimited file will also place double quotes around String fields. One uses sequential file access when the application reads all the data at once or writes all the data at once. Either a fixed-width or a comma-delimited file can be used. A comma-delimited file can save space if many of the strings’ average sizes are significantly smaller than their maximums. A fixed-width file sets size limits on the fields that are not required with comma-delimited files. The Visual Basic .NET Coach

5 The Visual Basic .NET Coach
Chapter 9 – Files 9.2 Fixed-Width Files Visual Basic .NET provides an object interface for accessing fixed-width formatted files. You can access a file for both input and output by using a combination of three classes—FileStream, StreamWriter, and StreamReader. In order to access these classes, you must include the namespace System.IO with an Imports statement at the beginning of your file. The Visual Basic .NET Coach

6 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Step 1: Add the Imports statement to the project at the top of your form. Imports System.IO The Visual Basic .NET Coach

7 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 2: When reading fixed-width files it is easiest to read data from a file one line at a time and then divide the data read into individual values. To accomplish this you first must open the text file using the FileStream object. Dim FileStreamName As New FileStream("Path and File Name", _ FileMode.Open, FileAccess.Read) Dim FileStreamName As New FileStream("Path and File Name", _ FileMode.OpenOrCreate, FileAccess.Write) FileStreamName is the name of the object that you will use to reference the file from within the application. The first parameter is the path to the file and the actual file name of the file that you are opening. The second parameter specifies the action upon opening the file: Append, Create, CreateNew, Open, OpenOrCreate, or Truncate. Use the Open keyword when opening a file for input and the OpenOrCreate keyword to write to a file. The final parameter indicates the action(s) that will be performed upon the file once it is open: Read, ReadWrite, or Write. Use the Read keyword for input and the Write keyword to write to a file. When you specify ReadWrite, the file can be either read from or written to. The Visual Basic .NET Coach

8 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 3: While the FileStream object will open the file, you need another object to perform an action on the file. The two typical actions to perform are reading and writing to the file. Visual Basic .NET includes two objects, the StreamReader and the StreamWriter. A StreamReader object allows to read data easily from the file just opened. Instantiating a StreamReader object requires passing it a FileStream object: Dim StreamReaderName As New StreamReader(FileStreamName) A StreamWriter object allows to write data from the file just opened: Dim StreamWriterName As New StreamWriter(FileStreamName) The Visual Basic .NET Coach

9 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 4: Once you have a StreamReader or StreamWriter object instantiated, you can read or write a line of data using the following syntax: strStringVariable = srStreamReaderVariable.ReadLine() or srStreamWriterVariable.WriteLine(strStringVariable) In the case of the StreamReader, a line of input is read from the file and stored in a String variable. In the case of the StreamWriter, a String variable is passed to the object and written to the file. The Visual Basic .NET Coach

10 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 5a: In order to read data from a fixed-width file, you must divide the single String read using the ReadLine method of the StreamReader object. This can be accomplished using the Substring method of the String class. The Visual Basic .NET Coach

11 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 5b: In order to write data to a fixed-width file, you must format the data so that the appropriate number of spaces follow each data element. The following is what two strings, "Jeff" and "Salvage", each padded to 10 characters, would look like if they were concatenated together: "Jeff Salvage " If the two strings were not padded, but still concatenated, they would look as follows: "JeffSalvage" The Visual Basic .NET Coach

12 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 5b continued: By passing PadRight the maximum size of the String as a parameter, you can automatically pad the String to the right size. Observe how you might declare a String, initialize it to "Jeff", and then pad it to 10 characters: Dim strFirstName As String strFirstName = "Jeff" strFirstName.PadRight(10) The Visual Basic .NET Coach

13 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 5b continued: What would happen if the initial String was initialized as follows? Dim strFirstName As String strFirstName = " Jeff" strFirstName.PadRight(10) The previous code would pad the String so that in the end it contained the following: " Jeff " To strip the initial spaces from the front of the String call the Trim method before you call the PadRight method. strFirstName.Trim.PadRight(10) By calling the Trim and PadRight methods with the size you wish the String to be, the String will be stripped of any spaces to the left and have the appropriate number of spaces appended to the right. To build the String that you will output, you can use the following syntax: 'First data field in the line strOutputLine = strValue1.Trim.PadRight(intstrValue1Size) 'Second data field in the line as well as any others strOutputLine &= strValue2.Trim.PadRight(intstrValue2Size) The Visual Basic .NET Coach

14 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 6: To check to see if you have reached the end of a file, compare the result of the Peek method of the StreamReader object to –1. A value of –1 indicates that you are at the end of the file and there is no additional data to be read. Set up a loop that checks to see if you have reached the end of file before you read the next line. The Visual Basic .NET Coach

15 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Fixed-Width Files Continued Step 7: The last step in accessing files is to close the objects that access the file (and thus the file itself) when you are done. When reading a file, you must close the StreamReader and the FileStream objects. When writing a file, you must close the StreamWriter and FileStream objects. All objects can be closed by calling the Close methods of each class. Observe the following syntax: StreamReaderName.Close() FileStreamName.Close() or StreamWriter.Close() FileStreamName.Close() The Visual Basic .NET Coach

16 The Visual Basic .NET Coach
Chapter 9 – Files Example: Fixed-Width Student Grades Application Problem Description Previously, you created an application that allowed the user to enter a student’s number, name, GPA, major, and year. Each time the application was executed, all the information had to be entered again. With the use of files, you can store the information you enter in a fixed-width file and then load it when the application starts. Problem Discussion The majority of the application will remain the same. The only visible change is that you will add a Save button to the application to allow any changes that have been made to the file. The Visual Basic .NET Coach

17 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution 1. You must load the information stored in the file so that it may be used by the application. 2. You must allow the user to save the changes made to the data. To load the information stored in the text file, you can require the user of the application to take a manual step, like clicking on a button, or you can have the information stored in the file loaded automatically when the application is executed. The latter solution is preferable. By placing the code to load information from the file in the form’s constructor, you can be assured that the information is loaded each time the application is executed. Your application will store its information in the file Students.txt located with the application in the bin directory so that you do not have to specify a directory for the file. The Visual Basic .NET Coach

18 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The code opens the fixed-text file and adds a row to the grdStudents MS flex grid for each line in the input file: Dim strInputLine As String Dim fs As New FileStream("Students.txt", FileMode.Open, _ FileAccess.Read) Dim srStudents As New StreamReader(fs) 'Loop through the input file Do While Not (srStudents.Peek = -1) strInputLine = srStudents.ReadLine() grdStudents.Rows += 1 grdStudents.Row = grdStudents.Rows -1 'Student # grdStudents.Col = 0 grdStudents.Text = strInputLine.Substring(0, 5).Trim() 'Last Name grdStudents.Col = 1 grdStudents.Text = strInputLine.Substring(5, 10).Trim() The Visual Basic .NET Coach

19 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued Constructor continued: 'First Name grdStudents.Col = 2 grdStudents.Text = strInputLine.Substring(15, 10).Trim() 'GPA grdStudents.Col = 3 grdStudents.Text = strInputLine.Substring(25, 5).Trim() 'Major grdStudents.Col = 4 grdStudents.Text = strInputLine.Substring(30, 25).Trim() 'Year grdStudents.Col = 5 grdStudents.Text = strInputLine.Substring(55, 10).Trim() Loop fs.Close() srStudents.Close() The Visual Basic .NET Coach

20 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The other code you must add to your application is the code required to save the data in the MS flex grid to the text file. Open the Students.txt with a FileMode of OpenOrCreate. You can output the data in the MS flex grid by looping through each row of the grid, excluding the first, and building a String containing an entire row’s data. After a row of data from the MS flex grid is contained in a String, write it to the file with the WriteLine method of the StreamWriter. Call the close methods of the StreamWriter and FileStream when you are done. Private Sub btnSave_Click(... Dim strOutputLine As String Dim intCurrentRow As Integer Dim fs As New FileStream("Students.txt", FileMode.OpenOrCreate, _ FileAccess.Write) Dim swStudents As New StreamWriter(fs) intCurrentRow = 1 The Visual Basic .NET Coach

21 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued btnSave_Click continued: Do While (intCurrentRow < grdStudents.Rows) 'Student # grdStudents.Row = intCurrentRow grdStudents.Col = 0 strOutputLine = grdStudents.Text.Trim.PadRight(5) 'Last Name grdStudents.Col = 1 strOutputLine &= grdStudents.Text.Trim.PadRight(10) 'First Name grdStudents.Col = 2 'GPA grdStudents.Col = 3 strOutputLine &= grdStudents.Text.Trim.PadRight(5) 'Major grdStudents.Col = 4 strOutputLine &= grdStudents.Text.Trim.PadRight(25) 'Year grdStudents.Col = 5 swStudents.WriteLine(strOutputLine) intCurrentRow += 1 Loop swStudents.Close() fs.Close() End Sub The Visual Basic .NET Coach

22 The Visual Basic .NET Coach
Chapter 9 – Files Drill 9.1 Write the code required to read four String values from the fixed-formatted data file DrillFile.txt into four String variables: strString1, strString2, strString3, and strString4. The maximum size of the four Strings are 10, 20, 15, and 25, respectively. Answer: Dim fs As New FileStream("DrillFile.txt", FileMode.Open, _ FileAccess.Read) Dim srDrill As New StreamReader(fs) Dim strString1 As String Dim strString2 As String Dim strString3 As String Dim strString4 As String Dim strInputLine As String strInputLine = srDrill.ReadLine() strString1 = Trim(strInputLine.Substring(0, 10)) strString2 = Trim(strInputLine.Substring(10, 20)) strString3 = Trim(strInputLine.Substring(1, 15)) strString4 = Trim(strInputLine.Substring(1, 25)) srDrill.Close() fs.Close() The Visual Basic .NET Coach

23 The Visual Basic .NET Coach
Chapter 9 – Files Drill 9.2 Write the code required to write four String values to the fixed-formatted data file DrillFile.txt from four String variables: strString1, strString2, strString3, and strString4. The maximum size of the four Strings are 10, 20, 15, and 25, respectively. Answer: Dim fs As New FileStream("DrillFile.txt", FileMode.Create, _ FileAccess.Write) Dim srDrill As New StreamWriter(fs) Dim strString1 As String Dim strString2 As String Dim strString3 As String Dim strString4 As String strString1 = "Some Value 1" strString2 = "Some Value 2" strString3 = "Some Value 3" strString4 = "Some Value 4" srDrill.WriteLine(PadRight(strString1, 10) & PadRight(strString2, 20) &_ PadRight(strString3, 15) & PadRight(strString4, 25)) srDrill.Close() fs.Close() The Visual Basic .NET Coach

24 The Visual Basic .NET Coach
Chapter 9 – Files 9.3 Comma-Delimited Files General Access of Comma-Delimited Files Step 1: Add the Imports statement to the project. Imports System.IO Step 2: When reading comma-delimited files, you read data into a series of variables, one for each field in the file. You will require a variable for each field in the record that you are reading. It is best to declare these at the beginning of the code. The Visual Basic .NET Coach

25 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Comma-Delimited Files Continued Step 3: To open the file use the FileOpen function: FileOpen(FileNumber, "Path and File Name", OpenMode.Input) Observe the following syntax for opening a file to write data: FileOpen(FileNumber, "Path and File Name", OpenMode.Output) The first parameter, FileNumber, is an Integer used as a handle to the file once it is opened. The number must be different from any other file numbers of any other simultaneously opened files. The second parameter is the file path to the file that you are opening. The third parameter specifies the action upon opening the file: Append, Binary, Input, Output, or Random. When you wish to read data from a file, use Input; and when you wish to write data to the file, use Output. The Visual Basic .NET Coach

26 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Comma-Delimited Files Continued Step 4: Once the file is opened, you can either read or write data from the file. To read data from the file, use the Input function. Input accepts two parameters. The first is the file number of the file to read from. The second is a variable to store the value that is read from the file. Only one value can be read at a time: Input(FileNumber, Value) To write values to a file use the WriteLine function. The first parameter is the file number of the file to write to. Unlike the Input function, the WriteLine function will allow you to write as many variables as you wish with one function call. WriteLine(FileNumber, Value1, Value2, Value3, Value4 ...) The Visual Basic .NET Coach

27 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Comma-Delimited Files Continued Step 5: To check to see if you have reached the end of a file call the EOF function. EOF will return True if the file number passed to it is at the end of file. Otherwise, it will return False. Step 6: The last step in accessing files is to close the file. Whether you opened the file for input or output, call the FileClose function with the file number of the file you wish to close: FileClose(FileNumber) The Visual Basic .NET Coach

28 The Visual Basic .NET Coach
Chapter 9 – Files Example: Comma-Delimited Student Grades Application Problem Description Change the previous application now so it contains the same functionality and ability to save and load its data, but implement it with a comma-delimited file instead of a fixed-width file. Problem Discussion The only two changes required to this application are to the constructor of the form and the btnSave button’s Click event. The application would look identical. The Visual Basic .NET Coach

29 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Load the data stored in the file so when the application starts, you have access to the data. Provide a way for users to save their changes as they feel it is appropriate. Set the loading of the data contained in the file to occur in the constructor of the form. This way the data is loaded each time the application is executed. Your application will store its data in the file Students.txt located with the application so that you do not have to specify a directory for the file. The Visual Basic .NET Coach

30 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The code opens the comma-delimited text file and adds a row to the grdStudents MS flex grid for each line in the input file. Continue reading data from the file until the EOF function indicates that you have processed the entire file. You cannot read all of the data elements on a single line of the file in a single command as before. Instead, you will have to call the Input function for each field in the file. Dim intStudentNumber As Integer Dim strLastName As String Dim strFirstName As String Dim sngGPA As Single Dim strMajor As String Dim strYear As String Dim intStudentFile As Integer intStudentFile = FreeFile() FileOpen(intStudentFile, "Students.txt", OpenMode.Input) Do While Not (EOF(intStudentFile)) 'Read each of the fields from the file Input(intStudentFile, intStudentNumber) Input(intStudentFile, strLastName) Input(intStudentFile, strFirstName) Input(intStudentFile, sngGPA) Input(intStudentFile, strMajor) Input(intStudentFile, strYear) The Visual Basic .NET Coach

31 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued Constructor continued: grdStudents.Rows += 1 grdStudents.Row -= grdStudents.Rows - 1 'Student # grdStudents.Col = 0 grdStudents.Text = intStudentNumber.ToString 'Last Name grdStudents.Col = 1 grdStudents.Text = strLastName 'First Name grdStudents.Col = 2 grdStudents.Text = strFirstName 'GPA grdStudents.Col = 3 grdStudents.Text = sngGPA.ToString 'Major grdStudents.Col = 4 grdStudents.Text = strMajor'Year grdStudents.Col = 5 grdStudents.Text = strYear Loop FileClose(intStudentFile) The Visual Basic .NET Coach

32 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued Add to your application the code required to save the data in the MS flex grid to the text file. You need to open the Students.txt file so that you can write your data to it. Once your file is open, you can output the data in your MS flex grid by looping through each row of the grid, excluding the first, and copy each row’s data to individual variables. After all of the data is written to the file, you must close the file using the FileClose function. Private Sub btnSave_Click(... Dim strOutputLine As String Dim intCurrentRow As Integer Dim intStudentFile As Integer Dim intStudentNumber As Integer Dim strLastName As String Dim strFirstName As String Dim sngGPA As Single Dim strMajor As String Dim strYear As String intStudentFile = FreeFile() FileOpen(intStudentFile, "Students.txt", OpenMode.Output) intCurrentRow = 1 The Visual Basic .NET Coach

33 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued btnSave_Click continued: Do While (intCurrentRow < grdStudents.Rows) 'Student # grdStudents.Row = intCurrentRow grdStudents.Col = 0 intStudentNumber = Val(grdStudents.Text) 'Last Name grdStudents.Col = 1 strLastName = grdStudents.Text 'First Name grdStudents.Col = 2 strFirstName = grdStudents.Text 'GPA grdStudents.Col = 3 sngGPA = Val(grdStudents.Text) 'Major grdStudents.Col = 4 strMajor = grdStudents.Text 'Year grdStudents.Col = 5 strYear = grdStudents.Text 'Output the data to the file WriteLine(intStudentFile, intStudentNumber, strLastName, _ strFirstName, sngGPA, strMajor, strYear) intCurrentRow += 1 Loop FileClose(intStudentFile) End Sub The Visual Basic .NET Coach

34 The Visual Basic .NET Coach
Chapter 9 – Files Drill 9.3 Write the code required to read four String values from the comma-delimited data file DrillFile.txt into four String variables: strString1, strString2, strString3, and strString4. Answer: Dim intDrillFile As Integer Dim strString1 As String Dim strString2 As String Dim strString3 As String Dim strString4 As String intDrillFile = FreeFile() FileOpen(intDrillFile, "DrillFile.txt", OpenMode.Input) Input(intDrillFile, strString1) Input(intDrillFile, strString2) Input(intDrillFile, strString3) Input(intDrillFile, strString4) FileClose(intDrillFile) The Visual Basic .NET Coach

35 The Visual Basic .NET Coach
Chapter 9 – Files Drill 9.4 Write the code required to write four String values to the comma-delimited data file DrillFile.txt from four String variables: strString1, strString2, strString3, and strString4. Answer: Dim intDrillFile As Integer Dim strString1 As String Dim strString2 As String Dim strString3 As String Dim strString4 As String intDrillFile = FreeFile() FileOpen(intDrillFile, "DrillFile.txt", OpenMode.Output) strString1 = "Some Value 1" strString2 = "Some Value 2" strString3 = "Some Value 3" strString4 = "Some Value 4" WriteLine(intDrillFile, strString1, strString2, strString3, strString4) FileClose(intDrillFile) The Visual Basic .NET Coach

36 The Visual Basic .NET Coach
Chapter 9 – Files 9.4 Random Access Files Random access files allow you to access data in a file with much flexibility. You can move forward and back throughout the file reading or writing records as you go. You must have each record formatted to a single size. General Access of Random Access Files Step 1: Add the Imports statement to the project. Imports System.IO The Visual Basic .NET Coach

37 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Random Access Files Continued Step 2: You do not have to choose between opening a file for either input or output. When you open a file for random access, you can read or write data one record at a time. FileOpen(FileNumber, "Path and File Name", OpenMode.Random, , , _ Len(RecordStructure)) The last parameter is the size of the record containing the data to be stored in the file. The easiest way to determine this is to call the Len function and pass it a variable defined as a structure defining the record in the file. The Visual Basic .NET Coach

38 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Random Access Files Continued Steps 3 to 5 could occur in any order. Step 3: To retrieve a specific record from a file, you must first declare a structure, CurrentStructure, and a variable from that type, RecordStructure. Read a record specified by an Integer RecordNumber to read a record into the structure CurrentStructure: FileGet(FileNumber, CurrentStructure, RecordNumber) Step 4: To write a structure to the end of the file, you must first declare a structure, CurrentStructure, and a variable from that type, RecordStructure. The values you wish to write to the file must be copied to that structure. You can write the end of the file by specifying a record number one more than the total number of records currently in the file. FilePut(FileNumber, CurrentStructure, OneMoreThanTotalNumberOfRecords) The Visual Basic .NET Coach

39 The Visual Basic .NET Coach
Chapter 9 – Files General Access of Random Access Files Continued Step 5: Updating a record in a random access file is accomplished using the same code as writing a record initially. The only difference is that you must make sure that the record number is the same as the one you wish to update. Step 6: When you are finished accessing the file, you must close it. FileClose(FileNumber) The Visual Basic .NET Coach

40 The Visual Basic .NET Coach
Chapter 9 – Files Example: Random Access File Student Grades Application Problem Description This application will allow the user to enter a student number, and that student’s information will be displayed in a series of text boxes. The user can change the information while the application points to the student’s information. At any time the user can add a student by entering the new information and then clicking on the Add Student button. At any point the user can enter a new student number and retrieve that student’s information. If the information displayed has been changed and not saved, the changes will be lost. The application would look like this: The Visual Basic .NET Coach

41 The Visual Basic .NET Coach
Chapter 9 – Files Problem Discussion You need to declare a structure to store the record of data in a file. You have to use completely different routines to process the input and output from the file than in previous examples. The Visual Basic .NET Coach

42 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution You need a few declarations in the Declarations section of the form: a variable that will store the total number of records within the file, another variable to store the file identification number of the file you are opening. This could be hard coded, but it is better programming practice to allow Visual Basic .NET to pick it for you. A user-defined type that will provide the details for the format of your record within the file. Dim intTotalRecords As Integer Dim intStudentFile As Integer Dim Student As StudentRecord Structure StudentRecord Public intStudentNumber As Integer <VBFixedString(10)> Public strLastName As String <VBFixedString(10)> Public strFirstName As String Public sngGPA As Single <VBFixedString(20)> Public strMajor As String <VBFixedString(10)> Public strYear As String End Structure The Visual Basic .NET Coach

43 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued You need to get the file identification number that will refer to your data file from within the application. This will be stored in the variable intStudentFile. Then you must open the actual data file as a random access file. You need to calculate the total number of records. This can be accomplished by dividing the length of the file by the length of an individual record in the file. The code to add to the form’s constructor is as follows: intStudentFile = FreeFile() ' Open the new file with the FileOpen statement. FileOpen(intStudentFile, "Students.txt", OpenMode.Random, , , _ Len(Student)) intTotalRecords = LOF(intStudentFile) / Len(Student) The Visual Basic .NET Coach

44 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued To ensure that the file is closed properly, place the code to close the file in the destructor of the form as shown in the following code: FileClose(intStudentFile) The Visual Basic .NET Coach

45 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued When the butSearch button is clicked, you need to find the record indicated by the txtSearch text box. Once the information is gathered into the record, you can copy the contents to each corresponding TextBox. Private Sub butSearch_Click(... Dim Student As StudentRecord 'Get the record from the file FileGet(intStudentFile, Student, CInt(txtSearch.Text)) 'Copy the information from the student structure 'to the text boxes for display txtLast.Text = Student.strLastName txtFirst.Text = Student.strFirstName txtGPA.Text = Student.sngGPA txtMajor.Text = Student.strMajor txtYear.Text = Student.strYear End Sub The Visual Basic .NET Coach

46 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued Writing the individual records to the file is a matter of copying the values in the text boxes to their corresponding fields within the record, incrementing the record counter, and then placing the actual record in the file. It’s a good practice to clear the form of the previously entered values. Private Sub butAddStudent_Click(... Dim Student As StudentRecord 'Copy values from text boxes to student structure Student.strLastName = txtLast.Text Student.strFirstName = txtFirst.Text Student.sngGPA = txtGPA.Text Student.strMajor = txtMajor.Text Student.strYear = txtYear.Text 'increase the total number of records and 'determine the record number for the new record intTotalRecords += 1 'Place the new record in the file FilePut(intStudentFile, Student, intTotalRecords) 'Clear the text boxes for the next entry txtLast.Text = "" txtFirst.Text = "" txtMajor.Text = "" txtYear.Text = "" txtGPA.Text = "" End Sub The Visual Basic .NET Coach

47 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The code required to update a record does not vary much from the code to add a record. The main difference is that when you write the record to the file, you write it to the record number indicated by the txtSearch text box instead of 1 more than the total number of records currently in the file. Private Sub butUpdateStudent_Click(... Dim Student As StudentRecord 'Copy values from text boxes to student structure Student.strLastName = txtLast.Text Student.strFirstName = txtFirst.Text Student.sngGPA = txtGPA.Text Student.strMajor = txtMajor.Text Student.strYear = txtYear.Text 'Update the current record in the file FilePut(intStudentFile, Student, CInt(txtSearch.Text)) 'Clear the text boxes for the next entry txtLast.Text = "" txtFirst.Text = "" txtMajor.Text = "" txtYear.Text = "" txtGPA.Text = "" End Sub The Visual Basic .NET Coach

48 The Visual Basic .NET Coach
Chapter 9 – Files Case Study Problem Description Until now, the payroll system that you developed needed the information to be entered every time the application was executed. You need to add the ability to save data and then automatically reload it when the application starts up. Problem Discussion Using a random access file would be the poorest choice in this case. If you changed the problem description so that data was saved as it was changed, then a random access file format would be the best choice. With the stipulation that you will only save data upon exiting the application, there is no need for a random access file format. The choice is either to use a fixed-format file or a comma-delimited format. If size isn’t an issue, the fixed-format file is better, because when you open it in Notepad, it’s easier to read. Your implementation will follow this format. The Visual Basic .NET Coach

49 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution The constructor code starts as it did before; however, once the MSFlexGrid is formatted, you must then load the data in the CaseStudy.txt data file. You read in each line of data: divide the line into separate data values copy those values to their appropriate place in the MSFlexGrid. Dim fs As New FileStream("CaseStudy.txt", FileMode.Open, FileAccess.Read) Dim srPayroll As New StreamReader(fs) Dim strInputLine As String Do While (srPayroll.Peek <> -1) strInputLine = srPayroll.ReadLine() grdEmployees.Rows += 1 grdEmployees.Row = grdEmployees.Rows – 1 'Employee Number grdEmployees.Col = 0 grdEmployees.Text = grdEmployees.Row.ToString 'Employee Name grdEmployees.Col = 1 grdEmployees.Text = strInputLine.Substring(0, 20) The Visual Basic .NET Coach

50 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The constructor continued: 'Hours Worked grdEmployees.Col = 2 grdEmployees.Text = strInputLine.Substring(20, 10) 'Department grdEmployees.Col = 3 grdEmployees.Text = strInputLine.Substring(30, 15) 'Weekly Pay grdEmployees.Col = 4 grdEmployees.Text = strInputLine.Substring(45, 10) Loop srPayroll.Close() fs.Close() The Visual Basic .NET Coach

51 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued The destructor code needs to: open a file for output loop through all of the rows in the MSFlexGrid format each value to its proper size output the values as a single line to the data file. Dim fs As New FileStream("CaseStudy.txt", FileMode.OpenOrCreate, FileAccess.Write) Dim swPayroll As New StreamWriter(fs) Dim strOutputLine As String Dim intCurrentRow As Integer The Visual Basic .NET Coach

52 The Visual Basic .NET Coach
Chapter 9 – Files Problem Solution Continued For intCurrentRow = 1 To grdEmployees.Rows - 1 grdEmployees.Row = intCurrentRow 'Employee Name grdEmployees.Col = 1 strOutputLine = PadRight(grdEmployees.Text, 20) 'Hours Worked grdEmployees.Col = 2 strOutputLine &= PadRight(grdEmployees.Text, 10) 'Department grdEmployees.Col = 3 strOutputLine &= PadRight(grdEmployees.Text, 15) 'Weekly Pay grdEmployees.Col = 4 swPayroll.WriteLine(strOutputLine) Next intCurrentRow swPayroll.Close() fs.Close() The Visual Basic .NET Coach

53 The Visual Basic .NET Coach
Chapter 9 – Files Coach’s Corner Common Dialog Box You can use a built-in dialog box that will prompt the user to select a file from any accessible drive. It returns a string containing the path and the file name that can be used in your application to open the file. Two of the most useful common dialog boxes are the Open File dialog box and the Save File As dialog box. The Visual Basic .NET Coach

54 The Visual Basic .NET Coach
Chapter 9 – Files Common Dialog Box Continued While you will place an Open File or Save File As dialog box control on the form, just like any other control, it will not be visible when you run your application. Instead, it will appear below the form: The Visual Basic .NET Coach

55 The Visual Basic .NET Coach
Chapter 9 – Files Setting Attributes for a Common Dialog Box Once a control is placed on the form, you can specify attributes so that your dialog box behaves exactly the way you desire. Here are the most important ones: Title: Good application development provides users with directions to help clarify what they are trying to accomplish. Filter: By specifying the Filter attribute, you can limit the types of files displayed using standard file name wildcard patterns. In order to indicate a filter, you must first specify a description of the limitation as in "Text Files(*.txt)" and then the actual wildcard pattern to limit the files displayed as in "*.txt". These two specifications must be separated by the pipe symbol "|". To set the filter of the dialog box dlgExample to show only text files, use the following code: dlgExample.Filter = "Text Files(*.txt)|*.txt" InitialDirectory: If this attribute is left unspecified, then the dialog box will be opened using the current directory. If you wish the dialog box to open in another directory, specify it by assigning the InitialDirectory property to the directory path you wish to open. The Visual Basic .NET Coach

56 The Visual Basic .NET Coach
Chapter 9 – Files Open File Example The following code presents the user with a dialog box to show an Open File dialog box. It only shows text files and have a title of "Select a Text File". If you do not select a file, it displays a message to the user and exits the subroutine. Private Sub butOpenFile_Click(... Dim strTextFileName As String ' Variable to store filename 'Set file open dialog properties DlgFileOpen.Filter = "Text Files(*.txt)|*.txt" DlgFileOpen.Title = "Select a Text File" DlgFileOpen.ShowDialog() If (Len(DlgFileOpen.FileName) > 0) Then strTextFileName = DlgFileOpen.FileName 'Set variable to filename Else MsgBox("No File Selected") End If End Sub The Visual Basic .NET Coach

57 The Visual Basic .NET Coach
Chapter 9 – Files Save File Example The following code presents the user with a dialog box to show a File Save dialog box. It only shows text files and has a title of "Save Text File As". If you do not select a file, it displays a message to the user and exits the subroutine. Private Sub butSaveDialog_Click(... Dim strTextFileName As String ' Variable to store filename 'Set file save dialog properties DlgFileSave.Filter = "Text Files(*.txt)|*.txt" DlgFileSave.Title = "Select a Text File" dlgFileSave.ShowDialog() MsgBox(dlgFileSave.FileName) If (Len(dlgFileSave.FileName) > 0) Then strTextFileName = dlgFileSave.FileName 'Set variable to filename Else MsgBox("No File Selected") End If End Sub The Visual Basic .NET Coach


Download ppt "The Visual Basic .NET Coach"

Similar presentations


Ads by Google