Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reading & writing to files

Similar presentations


Presentation on theme: "Reading & writing to files"— Presentation transcript:

1 Reading & writing to files
In Visual Basic .NET

2 Lesson Objectives Understand how to read external files using System.IO.StreamReader Understand how to write to external files using System.IO.StreamWriter

3 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!

4 To read files in one go Dim objReader As New System.IO.StreamReader(filename) TextBox1.Text = objReader.ReadToEnd objReader.Close() .close() Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

5 To read files line by line
Uses the ReadLine()function Dim sr As New System.IO.StreamReader(filename) Do input =sr.ReadLine() Msgbox(input) Loop Until input Is Nothing Ideal for filling arrays or ListBoxes! The Peek method returns an integer value in order to determine whether the end of the file, or another error has occurred

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

7 To write to a file To overwrite text: To append text: Add some text:
Dim objWriter As New System.IO.StreamWriter(filename) To append text: Dim objWriter As New System.IO.StreamWriter(filename,True) Add some text: objWriter.Write(“some text”) Still need to close the file at the end objWriter.Close() .close() Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

8 Imports statement If you type Imports System.IO
Above the class declaration It enables you to reference the StreamReader or StreamWriter type directly Could save time? The Imports statement enables types that are contained in a given namespace to be referenced directly.

9 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 vbCrLf or vbNewLine 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.

10 Learning Review Name 1 thing you have learned this lesson
Name 1 thing you want to learn next lesson


Download ppt "Reading & writing to files"

Similar presentations


Ads by Google