1 / 112

Files and Streams in VB: Introduction, Data Hierarchy, Classes, and Case Study

Learn about files and streams in VB, including data hierarchy, file manipulation classes, and a case study on transaction processing.

Télécharger la présentation

Files and Streams in VB: Introduction, Data Hierarchy, Classes, and Case Study

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 17 – Files and Streams Outline17.1 Introduction17.2   Data Hierarchy17.3   Files and Streams17.4   Classes File and Directory17.5   Creating a Sequential-Access File17.6   Reading Data from a Sequential-Access File17.7   Random-Access Files17.8   Creating a Random-Access File17.9   Writing Data Randomly to a Random-Access File17.10   Reading Data Sequentially from a Random-Access File17.11   Case Study: A Transaction-Processing Program

  2. 17.1 Introduction • Variables and arrays • Only temporary • Variable “goes out of scope” • Program terminates • Files • Long term storage • Persistent data • Secondary Storage Devices • Magnetic disks • Optical disks • Magnetic tapes

  3. 17.2   Data Hierarchy • Data Hierarchy • Bit (Binary Digit) • Either zero or one • All data reduced to combinations of bits for processing • Byte • Eight bits • Character • Two bytes • Character set • Set of all characters used to program and represent data on a particular computer

  4. 17.2   Data Hierarchy • Data Hierarchy • Field • Group of characters that convey a meaning • Record • Group of several, related fields • File • Group of related records • Record key • Identifies record to a particular entity • Sequential file • Records stored in order of record-key

  5. Sally Black Tom Blue Judy Judy Green Green file Iris Orange Randy Red record Judy Field 01001010 byte (ASCII for J) 1 bit 17.2   Data Hierarchy Fig. 17.1 Data hierarchy.

  6. 17.3   Files and Streams • VB views file as sequential streams of bytes • Ends with end-of-file marker or specific byte number • VB opens file • Creates an object • Associates a stream with that object • Stream object properties: • Console.In • Returns standard input stream object • Console.Out • Returns standard output stream object • Console.Error • Returns standard error stream object

  7. 17.3   Files and Streams • BinaryFormatter • Serialization • Converting object into a format that can be written to a file without losing data • Deserialization • Reading format from file and reconstructing original object from it

  8. 17.3   Files and Streams • System.IO.Stream • Provides functionality for representing streams as bytes • FileStream • Read and write sequential-access and random-access files • MemoryStream • Transfer data directly to and from memory • BufferedStream • Transfer data to or from stream

  9. 1 2 3 4 5 6 7 8 9 …… n - 1 end of file marker 17.3   Files and Streams Fig. 17.2 Visual Basic’s view of an n-byte file.

  10. 17.4   Classes File and Directory • Directory • Used to organize files • The \ separator character • Used to separate directories and files in a path • C:\VisualBasic\MyFile • Class File • Used to manipulate and determine information about files • Cannot instantiate File objects • Class Directory • Used to manipulate directories

  11. 17.4   Classes File and Directory Fig. 17.3 Some methods of class File.

  12. 17.4   Classes File and Directory Fig. 17.4 Some methods of class Directory.

  13. Enables users to input afile or directory name Called every time theuser presses a key in the text box Determines whether the user-specified text is a file 1 ' Fig 17.5: FileTest.vb 2 ' Using classes File and Directory. 3 4 Imports System.IO 5 Imports System.Windows.Forms 6 7 Public Class FrmFileTest 8 Inherits Form 9 10 ' label that gives directions to user 11 Friend WithEvents lblDirections As Label 12 13 ' text boxes for inputting and outputting data 14 Friend WithEvents txtOutput As TextBox 15 Friend WithEvents txtInput As TextBox 16 17 ' Visual Studio .NET generated code 18 19 ' invoked when user presses key 20Protected Sub txtInput_KeyDown(ByVal sender As Object, _ 21 ByVal e As System.Windows.Forms.KeyEventArgs) Handles _ 22 txtInput.KeyDown 23 24 ' determine whether user pressed Enter key 25 If e.KeyCode = Keys.EnterThen 26 27 Dim fileName As String' name of file or directory 28 29 ' get user-specified file or directory 30 fileName = txtInput.Text 31 32 ' determine whether fileName is a file 33If File.Exists(fileName) Then 34 FileTest.vb

  14. The user-specified text is passedin to get some information on that file File is opened and read Determines whether the user-specified text is a directory Obtains String array of subdirectories in thespecified directory 35 ' get file's creation date, modification date, etc. 36 txtOutput.Text = GetInformation(fileName) 37 38 ' display file contents through StreamReader 39 Try 40 41 ' obtain reader and file contents 42 Dim stream As StreamReader 43 stream = New StreamReader(fileName) 44 txtOutput.Text &= stream.ReadToEnd() 45 46 ' handle exception if StreamReader is unavailable 47 Catch exceptionCatch As IOException 48 49 ' display error 50 MessageBox.Show("FILE ERROR", "FILE ERROR", _ 51 MessageBoxButtons.OK, MessageBoxIcon.Error) 52 53 End Try 54 55 ' determine whether fileName is a directory 56ElseIf Directory.Exists(fileName) Then 57 58 Dim directoryList As String() ' array for directories 59 Dim i As Integer 60 61 ' get directory's creation date, modification date, etc 62 txtOutput.Text = GetInformation(fileName) 63 64 ' obtain directory list of specified directory 65 directoryList = Directory.GetDirectories(fileName) 66 67 txtOutput.Text &= vbCrLf & vbCrLf & _ 68 "Directory contents:" & vbCrLf 69 FileTest.vb

  15. Display each element in thedirectory User-specified text ispassed in as variable 70 ' output directoryList contents 71 For i = 0To directoryList.Length - 1 72 txtOutput.Text &= directoryList(i) & vbCrLf 73 Next 74 75 ' notify user that neither file nor directory exists 76 Else 77 MessageBox.Show(txtInput.Text & " does not exist", _ 78 "FILE ERROR", MessageBoxButtons.OK, _ 79 MessageBoxIcon.Error) 80 End If 81 82 End If' determine whether user pressed Enter key 83 84 End Sub' txtInput_KeyDown 85 86 ' get information on file or directory 87Private Function GetInformation(ByRef fileName As String) _ 88 As String 89 90 Dim information As String 91 92 ' output that file or directory exists 93 information = fileName & " exists" & vbCrLf & vbCrLf 94 95 ' output when file or directory was created 96 information &= "Created : " & _ 97 File.GetCreationTime(fileName) & vbCrLf 98 99 ' output when file or directory was last modified 100 information &= "Last modified: " & _ 101 File.GetLastWriteTime(fileName) & vbCrLf 102 FileTest.vb

  16. 103 ' output when file or directory was last accessed 104 information &= "Last accessed: " & _ 105 File.GetLastAccessTime(fileName) & vbCrLf & vbCrLf 106 107 Return information 108 End Function' GetInformation 109 110 End Class' FrmFileTest FileTest.vb

  17. FileTest.vb

  18. Enables user to input a directory name 1 ' Fig 17.6: FileSearch.vb 2 ' Using regular expressions to determine file types. 3 4 Imports System.IO 5 Imports System.Text.RegularExpressions 6 Imports System.Collections.Specialized 7 Imports System.Windows.Forms 8 9 Public Class FrmFileSearch 10 Inherits Form 11 12 ' label that displays current directory 13 Friend WithEvents lblDirectory As Label 14 15 ' label that displays directions to user 16 Friend WithEvents lblDirections As Label 17 18 ' button that activates search 19 Friend WithEvents cmdSearch As Button 20 21 ' text boxes for inputting and outputting data 22 Friend WithEvents txtInput As TextBox 23 Friend WithEvents txtOutput As TextBox 24 25 ' Visual Studio .NET generated code 26 27 Dim currentDirectory As String = Directory.GetCurrentDirectory 28 Dim directoryList As String() ' subdirectories 29 Dim fileArray As String() ' files in current directory 30 31 ' store extensions found and number found 32 Dim found As NameValueCollection = New NameValueCollection() 33 FileSearch.vb

  19. Method cmdSearch_Clickis called if Enter is pressed Searches recursively throughthe user specified directory Determines whether theuser-specified text is a directory 34 ' invoked when user types in text box 35 Private Sub txtInput_KeyDown(ByVal sender As System.Object, _ 36 ByVal e As System.Windows.Forms.KeyEventArgs) _ 37 Handles txtInput.KeyDown 38 39 ' determine whether user pressed Enter 40 If (e.KeyCode = Keys.Enter) Then 41 cmdSearch_Click(sender, e) 42 EndIf 43 44 End Sub' txtInput_KeyDown 45 46 ' invoked when user clicks "Search Directory" button 47Private Sub cmdSearch_Click(ByVal sender As System.Object, _ 48 ByVal e As System.EventArgs) Handles cmdSearch.Click 49 50 Dim current As String 51 52 ' check for user input; default is current directory 53 If txtInput.Text <> ""Then 54 55 ' verify that user input is a valid directory name 56If Directory.Exists(txtInput.Text) Then 57 currentDirectory = txtInput.Text 58 59 ' reset input text box and update display 60 lblDirectory.Text = "Current Directory:" & vbCrLf & _ 61 currentDirectory 62 63 ' show error if user does not specify valid directory 64 Else 65 MessageBox.Show("Invalid Directory", "Error", _ 66 MessageBoxButtons.OK, MessageBoxIcon.Error) FileSearch.vb

  20. The directory name is passedto method SearchDirectory All files found are displayed A regular expression is definedto specify file searching criteria 67 68 Return 69 End If 70 71 End If 72 73 ' clear text boxes 74 txtInput.Text = "" 75 txtOutput.Text = "" 76 77 ' search directory 78 SearchDirectory(currentDirectory) 79 80 ' summarize and print results 81For Each current In found 82 txtOutput.Text &= "* Found " & found(current) & " " _ 83 & current & " files." & vbCrLf 84 Next 85 86 ' clear output for new search 87 found.Clear() 88 End Sub' cmdSearch_Click 89 90 ' search directory using regular expression 91 Private Sub SearchDirectory(ByVal currentDirectory As String) 92 93 ' for file name without directory path 94 Try 95 Dim fileName As String = "" 96 Dim myFile As String 97 Dim myDirectory As String 98 99 ' regular expression for extensions matching pattern 100Dim regularExpression As Regex = _ 101 New Regex("([a-zA-Z0-9]+\.(?<extension>\w+))") FileSearch.vb

  21. Iterates through eachfile in the current directory String processing removes the path from the file name Checks if file matches theregular expression String is tagged with thename extension 102 103 ' stores regular-expression-match result 104 Dim matchResult As Match 105 106 Dim fileExtension As String' holds file extensions 107 108 ' number of files with given extension in directory 109 Dim extensionCount As Integer 110 111 ' get directories 112 directoryList = _ 113 Directory.GetDirectories(currentDirectory) 114 115 ' get list of files in current directory 116 fileArray = Directory.GetFiles(currentDirectory) 117 118 ' iterate through list of files 119For Each myFile In fileArray 120 121 ' remove directory path from file name 122 fileName = myFile.Substring( _ 123 myFile.LastIndexOf("\") + 1) 124 125 ' obtain result for regular-expression search 126 matchResult = regularExpression.Match(fileName) 127 128 ' check for match 129If (matchResult.Success) Then 130 fileExtension = matchResult.Result("${extension}") 131 Else 132 fileExtension = "[no extension]" 133 End If 134 FileSearch.vb

  22. Counts total numberof files with a particular extension type If a files extension typeis .bak then a message box prompts the user 135 ' store value from container 136 If (found(fileExtension) = Nothing) Then 137 found.Add(fileExtension, "1") 138 Else 139 extensionCount = _ 140 Convert.ToInt32(found(fileExtension)) + 1 141 142 found(fileExtension) = extensionCount.ToString() 143 End If 144 145 ' search for backup(.bak) files 146 If fileExtension = "bak"Then 147 148 ' prompt user to delete (.bak) file 149 Dim result As DialogResult = _ 150 MessageBox.Show("Found backup file " & _ 151 fileName & ". Delete?", "Delete Backup", _ 152 MessageBoxButtons.YesNo, _ 153 MessageBoxIcon.Question) 154 155 ' delete file if user clicked 'yes' 156 If (result = DialogResult.Yes) Then 157 File.Delete(myFile) 158 extensionCount = _ 159 Convert.ToInt32(found("bak")) - 1 160 161 found("bak") = extensionCount.ToString() 162 End If 163 164 End If 165 FileSearch.vb

  23. Iterates through allsubdirectories 166 Next 167 168 ' recursive call to search files in subdirectory 169ForEach myDirectory In directoryList 170 SearchDirectory(myDirectory) 171 Next 172 173 ' handle exception if files have unauthorized access 174 Catch unauthorizedAccess As UnauthorizedAccessException 175 MessageBox.Show("Some files may not be visible due to" _ 176 & " permission settings", "Warning", _ 177 MessageBoxButtons.OK, MessageBoxIcon.Information) 178 179 End Try 180 181 End Sub' SearchDirectory 182 183 End Class' FrmFileSearch FileSearch.vb

  24. FileSearch.vb

  25. 17.5   Creating a Sequential-Access File • VB imposes no structure on files • Concepts like “record” do not exist • Programmers must structure files to meet the requirements of applications

  26. Four text boxes in whichthe users can input data The number of text boxeson the form is set 1 ' Fig 17.7: BankUI.vb 2 ' A reusable windows form for the examples in this chapter. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmBankUI 7 Inherits Form 8 9 ' labels for TextBoxes 10 Public WithEvents lblAccount As Label 11 Public WithEvents lblFirstName As Label 12 Public WithEvents lblLastName As Label 13 Public WithEvents lblBalance As Label 14 15 ' text boxes that receive user input 16Public WithEvents txtAccount As TextBox 17 Public WithEvents txtFirstName As TextBox 18 Public WithEvents txtLastName As TextBox 19 Public WithEvents txtBalance As TextBox 20 21 ' Visual Studio .NET generated code 22 23 ' number of TextBoxes on Form 24Protected TextBoxCount As Integer = 4 25 26 ' enumeration constants specify TextBox indices 27 Public Enum TextBoxIndices 28 ACCOUNT 29 FIRST 30 LAST 31 BALANCE 32 End Enum 33 BankUI.vb

  27. For structure iterates throughevery control on the form Sets their values equal to an empty String Sets the values of the text boxes to the String-array values 34 ' clear all TextBoxes 35 Public Sub ClearTextBoxes() 36 Dim myControl As Control ' current GUI component 37 Dim i As Integer 38 39 ' iterate through every Control on form 40For i = 0To Controls.Count - 1 41 myControl = Controls(i) ' get Control 42 43 ' determine whether Control is TextBox 44 If (TypeOf myControl Is TextBox) Then 45 46 ' clear Text property (set to empty String) 47 myControl.Text = "" 48 End If 49 50 Next 51 52 End Sub' ClearTextBoxes 53 54 ' set TextBox values to String-array values 55Public Sub SetTextBoxValues(ByVal values As String()) 56 57 ' determine whether String array has correct length 58 If (values.Length <> TextBoxCount) Then 59 60 ' throw exception if not correct length 61 Throw New ArgumentException("There must be " & _ 62 TextBoxCount + 1 & " strings in the array") 63 BankUI.vb

  28. 64 ' else set array values to TextBox values 65 Else 66 txtAccount.Text = values(TextBoxIndices.ACCOUNT) 67 txtFirstName.Text = values(TextBoxIndices.FIRST) 68 txtLastName.Text = values(TextBoxIndices.LAST) 69 txtBalance.Text = values(TextBoxIndices.BALANCE) 70 End If 71 72 End Sub' SetTextBoxValues 73 74 ' return TextBox values as String array 75 Public Function GetTextBoxValues() As String() 76 77 Dim values(TextBoxCount) As String 78 79 ' copy TextBox fields to String array 80 values(TextBoxIndices.ACCOUNT) = txtAccount.Text 81 values(TextBoxIndices.FIRST) = txtFirstName.Text 82 values(TextBoxIndices.LAST) = txtLastName.Text 83 values(TextBoxIndices.BALANCE) = txtBalance.Text 84 85 Return values 86 End Function' GetTextBoxValues 87 88 End Class' FrmBankUI BankUI.vb

  29. Indicates to compiler thatobjects of class Crecordcan be serialized Sets the four membersto their default values Sets the members tospecified parameter values 1 ' Fig. 17.8: CRecord.vb 2 ' Serializable class that represents a data record. 3 4<Serializable()> Public Class CRecord 5 6 Private mAccount As Integer 7 Private mFirstName As String 8 Private mLastName As String 9 Private mBalance As Double 10 11 ' default constructor sets members to default values 12Public Sub New() 13 Me.New(0, "", "", 0.0) 14 End Sub' New 15 16 ' overloaded constructor sets members to parameter values 17 Public Sub New(ByVal accountValue As Integer, _ 18 ByVal firstNameValue As String, _ 19 ByVal lastNameValue As String, _ 20 ByVal balanceValue As Double) 21 22 Account = accountValue 23 FirstName = firstNameValue 24 LastName = lastNameValue 25 Balance = balanceValue 26 End Sub' New 27 28 ' property Account 29 Public Property Account() As Integer 30 31 Get 32 Return mAccount 33 End Get 34 CRecord.vb

  30. Methods for accessingthe data members 35 Set(ByVal accountValue As Integer) 36 mAccount = accountValue 37 End Set 38 39 End Property' Account 40 41 ' property FirstName 42Public Property FirstName() As String 43 44 Get 45 Return mFirstName 46 End Get 47 48 Set(ByVal firstNameValue As String) 49 mFirstName = firstNameValue 50 End Set 51 52 End Property' FirstName 53 54 ' property LastName 55 Public Property LastName() As String 56 57 Get 58 Return mLastName 59 End Get 60 61 Set(ByVal lastNameValue AsString) 62 mLastName = lastNameValue 63 End Set 64 65 End Property' LastName 66 67 ' property Balance 68 Public Property Balance() As Double 69 CRecord.vb

  31. 70 Get 71 Return mBalance 72 End Get 73 74 Set(ByVal balanceValue AsDouble) 75 mBalance = balanceValue 76 End Set 77 78 End Property' Balance 79 80 EndClass' CRecord CRecord.vb

  32. Inherits GUI similarto that of class FrmBankUIexcept has buttons Save As, Enter and Exit A save dialog box appearsand the user is prevented from interacting with any other window 1 ' Fig 17.9: CreateSequentialAccessFile.vb 2 ' Creating a sequential-access file. 3 4 ' Visual Basic namespaces 5 Imports System.IO 6 Imports System.Runtime.Serialization.Formatters.Binary 7 Imports System.Runtime.Serialization 8 Imports System.Windows.Forms 9 10 ' Deitel namespaces 11 Imports BankLibrary 12 13 Public Class FrmCreateSequentialAccessFile 14Inherits FrmBankUI 15 16 ' GUI buttons to save file, enter data and exit program 17 Friend WithEvents cmdSave As Button 18 Friend WithEvents cmdEnter As Button 19 Friend WithEvents cmdExit As Button 20 21 ' Visual Studio .NET generated code 22 23 ' serializes CRecord in binary format 24 Private formatter As BinaryFormatter = New BinaryFormatter() 25 26 ' stream through which serializable data is written to file 27 Private output As FileStream 28 29 ' invoked when user clicks Save button 30 Protected Sub cmdSave_Click(ByVal sender As Object, _ 31 ByVal e As System.EventArgs) Handles cmdSave.Click 32 33 ' create dialog box enabling user to save file 34 Dim fileChooser As SaveFileDialog = New SaveFileDialog() 35Dim result As DialogResult = fileChooser.ShowDialog() CreateSequentialAccessFile.vb

  33. Tests whether the userclicked Cancel Checks to make surethat a valid file has been selected FileStream object instantiated 36 Dim fileName AsString' name of file to save data 37 38 ' allow user to create file 39 fileChooser.CheckFileExists = False 40 41 ' exit event handler if user clicked "Cancel" 42If result = DialogResult.CancelThen 43 Return 44 End If 45 46 fileName = fileChooser.FileName ' get specified file name 47 48 ' show error if user specified invalid file 49If (fileName = ""OrElse fileName = Nothing) Then 50 MessageBox.Show("Invalid File Name", "Error", _ 51 MessageBoxButtons.OK, MessageBoxIcon.Error) 52 Else 53 54 ' save file via FileStream if user specified valid file 55 Try 56 57 ' open file with write access 58 output = New FileStream(fileName, _ 59 FileMode.OpenOrCreate, FileAccess.Write) 60 61 cmdSave.Enabled = False' disable Save button 62 cmdEnter.Enabled = True' enable Enter button 63 64 ' notify user if file does not exist 65 Catch fileException As FileNotFoundException 66 MessageBox.Show("File Does Not Exits", "Error", _ 67 MessageBoxButtons.OK, MessageBoxIcon.Error) 68 69 End Try CreateSequentialAccessFile.vb

  34. Textbox values are storedin an object of type CRecord 70 71 End If 72 73 End Sub ' cmdSave_Click 74 75 ' invoked when user clicks Enter button 76 Protected Sub cmdEnter_Click(ByVal sender As Object, _ 77 ByVal Be As System.EventArgs) Handles cmdEnter.Click 78 79 ' account-number value from TextBox 80 Dim accountNumber As Integer 81 82 ' store TextBox-values String array 83 Dim values As String() = GetTextBoxValues() 84 85 ' CRecord containing TextBox values to serialize 86 Dim record As New CRecord() 87 88 ' determine whether TextBox account field is empty 89 If values(TextBoxIndices.ACCOUNT) <> ""Then 90 91 ' store TextBox values in CRecord and serialize CRecord 92 Try 93 94 ' get account-number value from TextBox 95 accountNumber = _ 96 Convert.ToInt32(values(TextBoxIndices.ACCOUNT)) 97 98 ' determine whether accountNumber is valid 99 If accountNumber > 0Then 100 101 ' store TextBox fields in CRecord 102 record.Account = accountNumber 103 record.FirstName = values(TextBoxIndices.FIRST) 104 record.LastName = values(TextBoxIndices.LAST) CreateSequentialAccessFile.vb

  35. Writes the record to file Exception is handled ifuser entered an invalid format Method is invoked whenuser clicks Exit 105 record.Balance = Convert.ToDouble( _ 106 values(TextBoxIndices.BALANCE)) 107 108 ' write CRecord to FileStream (Serialize object) 109 formatter.Serialize(output, record) 110 111 ' notify user if invalid account number 112 Else 113 MessageBox.Show("Invalid Account Number", _ 114 "Error", MessageBoxButtons.OK, _ 115 MessageBoxIcon.Error) 116 End If 117 118 ' notify user if error occurs in serialization 119 Catch serializableException As SerializationException 120 MessageBox.Show("Error Writing to File", "Error", _ 121 MessageBoxButtons.OK, MessageBoxIcon.Error) 122 123 ' notify user if error occurs regarding parameter format 124Catch formattingException As FormatException 125 MessageBox.Show("Invalid Format", "Error", _ 126 MessageBoxButtons.OK, MessageBoxIcon.Error) 127 128 End Try 129 130 End If 131 132 ClearTextBoxes() ' clear TextBox values 133 End Sub' cmdEnter_Click 134 135 ' invoked when user clicks Exit button 136Protected Sub cmdExit_Click(ByVal sender As Object, _ 137 ByVal e As System.EventArgs) Handles cmdExit.Click 138 CreateSequentialAccessFile.vb

  36. 139 ' determine whether file exists 140 If (output Is Nothing) = False Then 141 142 ' close file 143 Try 144 output.Close() 145 146 ' notify user of error closing file 147 Catch fileException As IOException 148 MessageBox.Show("Cannot close file", "Error", _ 149 MessageBoxButtons.OK, MessageBoxIcon.Error) 150 151 End Try 152 153 End If 154 155 Application.Exit() 156 End Sub' cmdExit_Click 157 158 End Class' FrmCreateSequentialAccessFile CreateSequentialAccessFile.vb

  37. CreateSequentialAccessFile.vb

  38. CreateSequentialAccessFile.vb

  39. CreateSequentialAccessFile.vb

  40. 17.6   Reading Data from a Sequential-Access File • Sequential retrieval of data • Start at beginning of file and read data consecutively until the desired data are found • Sometimes necessary to process sequentially several times during execution • File-position pointer: • Points to next byte to be read from or written to file • Can be repositioned to any point in file

  41. 17.6   Reading Data from a Sequential-Access File Fig. 17.10 Sample data for the program of Fig. 17.9.

  42. Instantiates an object ofclass OpenFileDialog 1 ' Fig. 17.11: ReadSequentialAccessFile.vb 2 ' Reading a sequential-access file. 3 4 ' Visual Basic namespaces 5 Imports System.IO 6 Imports System.Runtime.Serialization.Formatters.Binary 7 Imports System.Runtime.Serialization 8 Imports System.Windows.Forms 9 10 ' Deitel namespaces 11 Imports BankLibrary 12 13 Public Class FrmReadSequentialAccessFile 14 Inherits FrmBankUI 15 16 ' GUI buttons for opening file and reading records 17 Friend WithEvents cmdOpen As Button 18 Friend WithEvents cmdNext As Button 19 20 ' Visual Studio .NET generated code 21 22 ' stream through which serializable data is read from file 23 Private input As FileStream 24 25 ' object for deserializing CRecord in binary format 26 Private reader As BinaryFormatter = New BinaryFormatter() 27 28 ' invoked when user clicks Open button 29 Protected Sub cmdOpen_Click(ByVal sender As Object, _ 30 ByVal e As EventArgs) Handles cmdOpen.Click 31 32 ' create dialog box enabling user to open file 33Dim fileChooser As OpenFileDialog = New OpenFileDialog() 34 Dim result As DialogResult = fileChooser.ShowDialog() 35 Dim fileName As String' name of file containing data ReadSequentialAccessFile.vb

  43. FileStreamobject is createdand assigned to reference input Method Next is called,which reads the next recordfrom the user-specified file Method Deserialize readsthe next record and caststhe result to a CRecord 36 37 ' exit event handler if user clicked Cancel 38 If result = DialogResult.CancelThen 39 Return 40 End If 41 42 fileName = fileChooser.FileName ' get specified file name 43 ClearTextBoxes() 44 45 ' show error if user specified invalid file 46 If (fileName = ""OrElse fileName = Nothing) Then 47 MessageBox.Show("Invalid File Name", "Error", _ 48 MessageBoxButtons.OK, MessageBoxIcon.Error) 49 Else ' open file if user specified valid file 50 51 ' create FileStream to obtain read access to file 52 input = New FileStream(fileName, FileMode.Open, _ 53 FileAccess.Read) 54 55 cmdNext.Enabled = True' enable Next Record button 56 57 End If 58 End Sub' cmdOpen_Click 59 60 ' invoked when user clicks Next button 61Protected Sub cmdNext_Click(ByVal sender As Object, _ 62 ByVal e As EventArgs) Handles cmdNext.Click 63 64 ' deserialize CRecord and store data in TextBoxes 65 Try 66 67 ' get next CRecord available in file 68 Dim record As CRecord = _ 69CType(reader.Deserialize(input), CRecord) 70 ReadSequentialAccessFile.vb

  44. The values are displayedin textboxes Exception is caught if record does not exist in the file 71 ' store CRecord values in temporary String array 72 Dim values As String() = New String() { _ 73 record.Account.ToString(), _ 74 record.FirstName.ToString(), _ 75 record.LastName.ToString(), _ 76 record.Balance.ToString()} 77 78 ' copy String-array values to TextBox values 79 SetTextBoxValues(values) 80 81 ' handle exception when no CRecords in file 82Catch serializableException As SerializationException 83 84 input.Close() ' close FileStream if no CRecords in file 85 86 cmdOpen.Enabled = True' enable Open Record button 87 cmdNext.Enabled = False' disable Next Record button 88 89 ClearTextBoxes() 90 91 ' notify user if no CRecords in file 92 MessageBox.Show("No more records in file", "", _ 93 MessageBoxButtons.OK, MessageBoxIcon.Information) 94 End Try 95 96 End Sub' cmdNext_Click 97 98 End Class' FrmReadSequentialAccessFile ReadSequentialAccessFile.vb

  45. ReadSequentialAccessFile.vb

  46. ReadSequentialAccessFile.vb

  47. ReadSequentialAccessFile.vb

  48. 1 ' Fig. 17.12: CreditInquiry.vb 2 ' Read a file sequentially and display contents based on account 3 ' type specified by user (credit, debit or zero balances). 4 5 ' Visual Basic namespaces 6 Imports System.IO 7 Imports System.Runtime.Serialization.Formatters.Binary 8 Imports System.Runtime.Serialization 9 Imports System.Windows.Forms 10 11 ' Deitel namespaces 12 Imports BankLibrary 13 14 Public Class FrmCreditInquiry 15 Inherits Form 16 17 ' displays several lines of output 18 Friend WithEvents txtDisplay As RichTextBox 19 20 ' buttons to open file, read records and exit program 21 Friend WithEvents cmdOpen As Button 22 Friend WithEvents cmdCredit As Button 23 Friend WithEvents cmdDebit As Button 24 Friend WithEvents cmdZero As Button 25 Friend WithEvents cmdDone As Button 26 27 ' Visual Studio .NET generated code 28 29 ' stream through which serializable data is read from file 30 Private input As FileStream 31 32 ' object for deserializing CRecord in binary format 33 Dim reader As BinaryFormatter = New BinaryFormatter() 34 CreditInquiry.vb

  49. Instantiates an object ofclass OpenFileDialog Displays an open dialog 35 ' name of file that stores credit, debit and zero balances 36 Private fileName As String 37 38 ' invoked when user clicks Open File button 39 Protected Sub cmdOpen_Click(ByVal sender As Object, _ 40 ByVal e As System.EventArgs) Handles cmdOpen.Click 41 42 ' create dialog box enabling user to open file 43Dim fileChooser As OpenFileDialog = New OpenFileDialog() 44Dim result As DialogResult = fileChooser.ShowDialog() 45 46 ' exit event handler if user clicked Cancel 47 If result = DialogResult.CancelThen 48 Return 49 End If 50 51 fileName = fileChooser.FileName ' get file name from user 52 53 ' enable buttons allowing user to display balances 54 cmdCredit.Enabled = True 55 cmdDebit.Enabled = True 56 cmdZero.Enabled = True 57 58 ' show error if user specified invalid file 59 If (fileName = "" OrElse fileName = Nothing) Then 60 MessageBox.Show("Invalid File Name", "Error", _ 61 MessageBoxButtons.OK, MessageBoxIcon.Error) 62 63 ' else enable all GUI buttons, except for Open File button 64 Else 65 cmdOpen.Enabled = False 66 cmdCredit.Enabled = True 67 cmdDebit.Enabled = True 68 cmdZero.Enabled = True 69 End If CreditInquiry.vb

  50. Casts the senderObjectparameter Extracts the Button object’s text Create FileStream object withread-only file access 70 71 End Sub' cmdOpen_Click 72 73 ' invoked when user clicks Credit Balances, Debit Balances 74 ' or Zero Balances button 75 Protected Sub cmdGet_Click(ByVal senderObject As Object, _ 76 ByVal e As System.EventArgs) Handles cmdCredit.Click, _ 77 cmdZero.Click, cmdDebit.Click 78 79 ' convert senderObject explicitly to object of type Button 80Dim senderButton As Button = CType(senderObject, Button) 81 82 ' get text from clicked Button, which stores account type 83Dim accountType As String = senderButton.Text 84 85 ' used to store each record read from file 86 Dim record As CRecord 87 88 ' read and display file information 89 Try 90 91 ' close file from previous operation 92 If (input Is Nothing) = False Then 93 input.Close() 94 End If 95 96 ' create FileStream to obtain read access to file 97 input = New FileStream(fileName, FileMode.Open, _ 98 FileAccess.Read) 99 100 txtDisplay.Text = "The accounts are:" & vbCrLf 101 CreditInquiry.vb

More Related