Reading writing to files In Visual Basic NET

Reading & writing to files In Visual Basic. NET

Lesson Objectives • Understand how to read external files using System. IO. Stream. Reader • Understand how to write to external files using System. IO. Stream. Writer

External files • Often need to access other files – Data is often stored in other files – produced from other systems – Need to write to files to save data • Often used in controlled assessment tasks!

To read files in one go Dim obj. Reader As New System. IO. Stream. Reader(filename) Text. Box 1. Text = obj. Reader. Read. To. End obj. Reader. Close()

To read files line by line • Uses the Read. Line()function Idea fillin l for g ar rays o List. B r oxes ! Dim sr As New System. IO. Stream. Reader(filename) Do input =sr. Read. Line() Msgbox(input) Loop Until input Is Nothing

Task 1: Reading a text file 1. Create a simple text file using Notepad storing a list of shopping items. 1. Note the file name and where it is saved 2. Create new VB project with form with a multiline text box that reads the text file and displays it 1. Use either Readto. End() or Read. Line() in a loop 3. Challenge – use System. IO. File. Exists(filename) to check the file exists before reading it

To write to a file To overwrite text: Dim obj. Writer As New System. IO. Stream. Writer(filename) To append text: Dim obj. Writer As New System. IO. Stream. Writer(filename, True) Add some text: obj. Writer. Write(“some text”) Still need to close the file at the end obj. Writer. Close()

Imports statement • If you type Imports System. IO Above the class declaration • It enables you to reference the Stream. Reader or Stream. Writer type directly • Could save time?

Task 2: Write to a text file • Add a text box and button to your form • On button click add code that writes the new value to your text file – Make the filename global so it can be accessed on form load and button click – Use vb. Cr. Lf or vb. New. Line to make it appear on new line – How would your reload text box to show the new addition? – Challenge – before adding the item use. Contains() to test if the entry exists in the list already.

Learning Review • Name 1 thing you have learned this lesson • Name 1 thing you want to learn next lesson
- Slides: 10