1 / 15

File I/O

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. Visual Basic Techniques for File I/O. Only Available in Visual Basic, not other .NET languages such as C# or JavaScript.

zada
Download Presentation

File I/O

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

  2. Visual Basic Techniques for File I/O • Only Available in Visual Basic, not other .NET languages such as C# or JavaScript. • Good for writing a single string • No need to open or close files. • General Forms: • Unless specified, files are created in bin\Debug of project. My.Computer.FileSystem.WriteAllText(FileName, StringToWrite, AppendBoolean) My.Computer.FileSystem.ReadAllText(Fileame)

  3. Some Simple Examples My.Computer.FileSystem.WriteAllText("Names.txt", “Rick Bournique, True) • This example appends Rick Bournique to the end of the names.txt file. • This example tries to open Names.txt and read the data in the file into the variable Name. Try Name = My.Computer.FileSystem.ReadAllText( "Names.txt") Catch MessageBox.Show("File or path not found or invalid") End Try

  4. Writing & Reading Delimited Files • You can write multiple fields into a file by separating the fields with a delimiter- a character that separates the fields. E.g., Jack,111-222-3333 Jill,444-555-6666 • Reading requires a TextFieldParser object: My.Computer.FileSystem.WriteAllText("Names.txt", StudentName & "," & StudentPhone & Environment.NewLine, True) Imports Microsoft,VisualBasic.FileIO Private NamePhoneParser As TextFieldParser NamePhoneParser = New TextFieldParser(FileString) NamePhoneParser.TextFieldType = FieldType.Delimited NamePhoneParser.SetDelimiters(“,”)

  5. Reading Fields with TextFieldParser • Once you’ve set up a TextFieldParser object, use the ReadFields() method to read the fields into an array you created: Dim TheName, ThePhone As String Dim FieldsArray() As String = NamePhoneParser.ReadFields() TheName = FieldsArray(0) ThePhone = FieldsArray(1)

  6. File Handling Using Streams • A stream is the transfer of a series of bytes from one location to another. • Streams are found in the System.IO namespace. Use an Imports statement. • Compared to the VB techniques , streams provide more robust and universal file handling in the .NET framework.

  7. Steps for Writing Data in a File Using Streams • Declare a new StreamWriter object. • Use the StreamWriter's WriteLine() method to copy data to a buffer in memory. • Call StreamWriter's Close() methodtotransfer data from buffer to the file and release system resources used by the stream.

  8. Step 1: Instantiating a StreamWriter Object Dim ObjectName As New StreamWriter("FileName") Dim ObjectName As New StreamWriter("FileName", BooleanAppend) • General Forms: • Default location for file is bin/Debug folder beneath the folder of the current project. • BooleanAppend lets you append data to an existing file rather than overwrite the existing file. Set to True to append. Dim MyStreamWriter As New StreamWriter("Phone.txt“)

  9. Step 2: Write the Data • Write() method places items consecutively in the file with no delimiter (separator) • WriteLine() method places an enter (carriage return) between the items • General Form: DataToWrite argument may be string or numeric data. Any numeric data is converted to a string. • Examples: StreamObjectName.WriteLine(DataToWrite) NameStreamWriter.WriteLine(“Rick Bournique”) IncomeStreamWriter.Write(50000)

  10. Step 3: Close the Stream • Use the StreamWriter'sClose() method. • Close() finishes writing all data from the stream's buffer to the disk and releases system resources. Commonly inserted in the form’s closing event procedure. • If the file is not closed, it may remain open for an indefinite time and sometimes may become unusable. • Example: Private Sub ExitButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ExitButton.Click PhoneStreamWriter.Close() Me.Close() End Sub

  11. Steps for Reading Data from a File Using Streams • Declare a new StreamReader object. This opens the file for reading. • Use the StreamWriter's ReadLine() method to get the data from the stream. Typically this statement is in a loop to get multiple records. • Call StreamReader's Close() methodtorelease system resources used by the stream.

  12. Step 1: Instantiating a StreamReader Object • Declare the StreamReader object in a procedure and enclose it in a Try/Catch block. • The file must exist in the specified location where the application expects it or an exception occurs. Try Dim MyStreamReader As New StreamReader(“who.txt“) Catch MessageBox.Show(“File does not exist.”) End Try

  13. Step 2: Read the Data • The ReadLine() method is used to read previously saved lines of data from the file. Typically this is in a loop to read multiple lines. • Assign the value from the read to the desired location, such as a label, text box, or string variable. Example • Note that ReadLine() has no arguments. PhoneTextBox.Text = PhoneStreamReader.ReadLine()

  14. Checking for the End of the File • Use StreamReader's. Peek() method to look at the next element without reading it. • If you Peek()beyond the last element, the value returned is -1. • Example: • The discussion of Peek() in the text and the example programs (starting on page 448) is full of errors! Peek() is a method and therefore requires () when used. If MyStreamReader.Peek() <> -1 Name.TextBox = MyStreamReader.ReadLine() End If

  15. Step 3: Close the Stream • The Close() method is used to terminate the stream. • Example: • Use the VB keyword Nothing to check for instantiation of the stream reader. • Syntax is important: use the keyword IsNot rather than <> If MyStreamReader IsNot Nothing MyStreamReader.Close() End If

More Related