0% found this document useful (0 votes)
4 views47 pages

Group 5 Presentation[1][1]

The presentation covers techniques for reading from and writing to files in Visual Basic, including input from text and delimited files. It outlines steps for file operations such as opening, reading, and closing files, along with example code for practical applications. The document also discusses the importance of handling exceptions and the daily use cases of file reading and writing in various contexts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views47 pages

Group 5 Presentation[1][1]

The presentation covers techniques for reading from and writing to files in Visual Basic, including input from text and delimited files. It outlines steps for file operations such as opening, reading, and closing files, along with example code for practical applications. The document also discusses the importance of handling exceptions and the daily use cases of file reading and writing in various contexts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Presentation on

Reading From File


and Output to a file.

THE ENLIGHTENING JOURNEY INTO BETTER


UNDERSTANDING FILES IN VISUASL BASIC
Presented by Group 5
Overview
 INTRODUCTION
 INPUT FROM A FILE
 READING FROM A FILE
 READING DELIMITED FILES
 OUTPUT TO A FILE
 EXAMPLE AND DEMOSTRATION
 Q&A
 CONCLUSION
INTRODUCTION

 In the Windows 11 operating system the Files explorer is


where we store all our files, documents, spreadsheets, and
folders
 Visual Basic also allows you to get input from different kinds of files
and it also allows you to write your output to different kinds of files as
well.
 We will explore the essential techniques for reading from and writing
to files using Visual Basic.
 Whether you're a beginner or an experienced developer,
understanding file operations is crucial for many programming tasks.
FILE INPUT /
OUTPUT
Input from a File
Reading from a text file, requires the follow three steps:

 Open the file for input


 Read from the file
 After information from the file has been read, close the
file
Input from a File
WAYS TO READ FROM A FILE :
 Reading the whole file at once
 Reading from the file line by line
 Reading a delimited file
 Reading fixed-width text file.
Reading data from the file

 A file is a specific name and folder path in computer


memory, used for operations on the file's path.
 There are different types of files which are: TXT, PDF, DOC and
DOCX.
 Visual Basic enables input and output from various file types,
specifically text files. To read text from a file, create a file reader
object, ensuring it exists before reading
 There are many ways we can read from a file like, reading from a file line
by line and reading a delimited file.
 Reading from a file line by line

 The ReadLine method reads text from a file line by line, counting
from the current position until the end of the line, depending on the
file's data storage.
 A while Loop is typically used to determine the number of items in a
file if it is not specified in the question
Opening the file for input

 STEP 1
The InputOutput(IO) class's streamreader data type is utilized to read
a stream of characters from a memory location from a file.
Dim variable name as IO. StreamReader
The StreamReader File specification establishes a communication
link between the computer and the disk drive, identifying the file to
be read
 STEP 2
Reading a data item from a file is done using the readline builtin
function.
StrVar = readerVar.Readline.
The data can be assigned to a numeric variable, in that case we use
Val function.
numVar = Val (readerVar.ReadLine)
StreamReader initializes an input marker at file start, moves to next
line at file end, and ends the file after reading the last line.

The StreamReader's Endofstream function is crucial for reading all


unknown items in a file with an unknown number of items
Closing the file

After reading from the file, the last step is to terminate the
communication link that was set up in Step 1.

readVar.Close()
DAILY USE

Reading from a file line by line, this is commonly used in schools when
they want to create a class list or to create a list for admitted students.
It is also used to take out numbers from a set of numbers e.g taking
prime numbers or integers.
Do’s Don’t
Dim variable name as IO. Do not make decisions about the
StreamReader contents of the file based on the
name of the file

Dim variable name as IO.


StreamReader Do not assume that the file is in a
specific format.

Do not assume that the file is small


enough to fit into memory.

Do not forget to handle exceptions


that may occur while reading the file.
Reading From Text Files Algorithms:
Question Paper Marker:
 Create a Stream reader variable to read the text file.
 Declare variables for the answer and an array for the answers from the memo.txt
 Declare i variable for handling the index of the memo array.
 Declare marks variable to calculate the total mark that the student receives.
 Close the file.
 Uses a Combo boxes and a text box to ask the student questions and take their answers.
 Uses If Statements to check if the answers from the different combo boxes and text box
are the same as the answers from the memo array, if they are, 1 is added to marks
variable.
 Displays that total mark on a Label.
EXAMPLE CODE 1
Private Sub Button1_Click() Handles Button1.Click
Dim readerVar As IO.StreamReader = IO.File.OpenText("C:\Users\HP\Desktop\Group 5
Presentation\memo.txt")
Dim answer As String
Dim memoAnswers(4) As String
Dim i As Integer = 0
Dim marks As Integer = 0

While Not readerVar.EndOfStream


answer = readerVar.ReadLine()
memoAnswers(i) = answer
i = i + 1
End While
readerVar.Close()
'Marks the student's answers by checking if they are the same as the answers from the
memo.txt'
If ComboBox1.Text = memoAnswers(0) Then
marks = marks + 1
End If
If ComboBox2.Text = memoAnswers(1) Then
marks = marks + 1
End If
If ComboBox3.Text = memoAnswers(2) Then
marks = marks + 1
End If
If ComboBox4.Text = memoAnswers(3) Then
marks = marks + 1
End If
If LCase(TextBox1.Text) = memoAnswers(4) Then
marks = marks + 1
End If
Label2.Text = marks & " / 5"
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object,


e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

End Sub

Private Sub QuestionPaperMarker_Load(sender As System.Object, e As


System.EventArgs) Handles MyBase.Load

End Sub
End Class
Reading a Delimited File
 What is a DELIMITED FILE ?

A delimited file is a text file used to store data and data in a delimited
text file is arranged in rows and columns, with one entry per row. Each
column is separated from the next by a field separator character/
a delimiter.

Our delimiter for our course is a comma(,)


DELIMITED FILE
DISADVANTAGES

1. They can be difficult to parse , as the delimiter character can also


occur within the data itself.

2. They can be difficult to handle if the data contains special


character that is a delimiter (such as a comma)

3. They can be difficult to use for data analysing, as they do not


provide any structure or metadata about the data.
DAILY USE

Reading a delimited file, this can be used in a business to take a


name, surname and the percentage of performance of the employee
throughout the month.
It is used in a clothing company to advertise the name, size and the
name of the brand.
It can also be used at an institution to state the name, surname,
student number and whether that particular learner has passed or not
Reading Delimited Files Algorithms:
School Litter Collection:
 Open data file using TextFieldParser and declare a variable that will
read it.
 Set the type of the text field.
 Set the value for the delimiter.
 Declare variables to store the table data.
 Declare the formatted string.
 Set the font for the list box table.
 Create a loop that will read the file.
 Store the data values from the file into the different table variables.
 Add the data to the list box table.
EXAMPLE CODE : 2
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles
Button1.Click
Using fReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\
Users\HP\Desktop\Group 5 Presentation\Reading Delimited Files\LitterWeight.txt")
fReader.TextFieldType = FileIO.FieldType.Delimited
fReader.SetDelimiters("#")
Dim currentRow As String()
Dim name As String
Dim metal, glass, paper, other As Single
Dim fmtStr As String = "{0, -35}{1,-8}{2,-9}{3,-7}{4,-10}"
Dim value As Font = New Font("Courier New", 10)
ListBox1.Font = value
ListBox1.Items.Add("School Trash Collection")
ListBox1.Items.Add("")
ListBox1.Items.Add(String.Format(fmtStr, "School Name", "Metal",
"Glass", "Paper", "Other"))
Cont…

While Not fReader.EndOfData


currentRow = fReader.ReadFields()
name = currentRow(0)
metal = Val(currentRow(1))
glass = Val(currentRow(2))
paper = Val(currentRow(3))
other = Val(currentRow(4))
ListBox1.Items.Add(String.Format(fmtStr, name, metal, glass,
paper, other))
End While

End Using
End Sub
Private Sub LitterData_Load(sender As System.Object, e As System.EventArgs)
Handles MyBase.Load
ListBox1.Text = "Litter Collection Data From Different Schools"
End Sub
End Class
Reading Delimited Files Algorithms:
 Check Your DP:
 Create Boolean Function stuAvail() that:
  Uses a Text field parser to read the marks.txt file.
 Declares variables for the student number and the Boolean
to check if the student number appears in the file.
 Sets the type of file being read.
 Sets delimiter.
 Uses while loop to read all fields and lines of the file and
uses and If statement to check if the student number is in the
file.
 Create Integer Function calcDP() that takes your student number as
an argument:
  Reads the file marks.txt like the previous function.
 Declares variables for the student number and different
assessment marks recorded in the txt file.
 Declares a variable that will store the DP.
 Uses a while loop to read through the text file.
 Sets the different variables to the different data values from the text
file.
 Uses an If statement to search for the student number and when it
finds it, it uses the other values to calculate the DP.
 Returns DP
 Uses the two functions to calculate your DP from inputting your
student number.
EXAMPLE CODE 3
Public Class CheckYourDP
Function stuAvail(ByVal stuNum As Integer) As Boolean
Using marksDB As New
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\
Users\HP\Desktop\Group 5 Presentation\Reading
Delimited Files\marks.txt")
Dim currentStudent As String()
Dim studentNumber As Integer
Dim studentAvailability As Boolean
marksDB.TextFieldType =FileIO.FieldType.Delimited
marksDB.SetDelimiters(",")
Cont…
While Not marksDB.EndOfData
currentStudent = marksDB.ReadFields()
studentNumber =Val(currentStudent(0))
If studentNumber = stuNum Then
studentAvailability = True
Else
studentAvailability = False
End If
End While
Return studentAvailability
End Using
End Function
EXAMPLE CODES
Function calcDP(ByVal student_no As Integer) As Single
Using marksDB As New
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\HP\Desktop\Group
5 Presentation\Reading Delimited Files\marks.txt")
Dim currentStudent As String()
Dim studentNumber, assMark, pracMark, test1, test2 As
Integer
Dim DP As Single
marksDB.TextFieldType = FileIO.FieldType.Delimited
marksDB.SetDelimiters(",")
Cont…
While Not marksDB.EndOfData
currentStudent = marksDB.ReadFields()
studentNumber = Val(currentStudent(0))
assMark = Val(currentStudent(1))
pracMark = Val(currentStudent(2))
test1 = Val(currentStudent(3))
test2 = Val(currentStudent(4))
If studentNumber = student_no Then
DP = ((Val(assMark) / 100 * 100) * 0.1)
((Val(pracMark) / 20 * 100) * 0.2) + ((Val(test1) / 50 * 100)
* 0.35) + ((Val(test2) / 50 * 100) * 0.35)
End If
End While
Return DP
End Using
End Function
EXAMPLE CODE 4
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles
Button1.Click
Dim your_stuNum As Integer = TextBox1.Text

Dim checkAvailability As Boolean


checkAvailability = stuAvail(your_stuNum)

If checkAvailability = True Then

Console.Write("Your DP is " & calcDP(TextBox1.Text) & "%")

checkAvailability = True

Else

MsgBox("This student number does not exist. Try again or contact


administrator")

TextBox1.Clear()

checkAvailability = False

End If

End Sub
Output to a File
 What is an output ?
Output means to produce results, results that can be displayed on
screen, written to a printer or to a file, in this topic we will be focusing
on outputting to a file.

 Which file are we speaking about?


A delimited file, Text files,
So for us to actually produce results or rather have an output, we
have steps to follow,
 Step 1: Opening a File
To write to a File we use a data type called StreamWriter.
A streamWriter is a common class in the Visual Basic Programming
network that writes data to a text file, either lines or strings.
The streamWriter is Declared in the following Format :

FileWriter As IO.StreamWriter

Where : FileWriter(Variable)
IO(Input Output Class)
Streamwriter(Datatype)
Cont…
To initialise the Streamwriter we need to give it the file name and
location in following manner

FileWriter = New System.IO.Streamwriter(“FileName.Txt”,True)

This can be initialised in one line like other Variables in the following
way

Dim FileWriter As IO.StreamWriter =New System.IO.Streamwriter(“FileName.Txt”,True)


Do’s
 You must always write True after the mentioning of the file name so that the
program can execute even if the file does not exist, Visual basic will create a file
for you. If you write false the program will not execute.
 Step 2 : Writing data to the File

When we’re inserting Data to the file we use the Write Function or the
Write.Line Function.

The write Function will write all the data to a sequential file without
separating the data since the write function does not separate the
data you use the write.Line Function which writes data in the textfile
line by line.
The Write Function has the following format:

fw.Write = str(or num)

The Write.Line function has the following format different from the
write function

fw.Write.Line = str(or num)

you can either use the str or num, where str is string and num stands
for numerical value.
 Step3: Close the file
After you have written all the data you want to the file, you close the
file using the following format :

fw.close()
Do’s Don’t
 It advisable to use Write.Line Don't forget to close the file
function when you having a lot of
information to insert into your file
that uses different lines or rather
have separators
 For example when you want to
write the list of students taking
the CSC module, you will use the
Write. Line function.
Do’s Don’t
 it is imperative to close the file as  If you don’t close the file, all the
it makes sure that all your data is information you have written will
saved. erased.
 {}
Writing Delimited Files Algorithms:
Sign Up details storer:
 Declare a variable for the stream writer.
 Declare variables for name, surname, email, phone number, password and re-
entering the password.
 Use the variables to store values from different text boxes you use to collect
information.
 Use an If statement to check if the two passwords match.
 If the do write the values of the variables in the generated file.
 If they do not match, clear the text boxes used to collect the two passwords
so you can re enter them.
EXAMPLE CODE : 5
Public Class signUp

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles


Button1.Click
Dim accountWriter As IO.StreamWriter = New System.IO.StreamWriter("C:\Users\
HP\Desktop\Group 5 Presentation\Writing Delimited Files\Accounts.txt", True)
Dim name, surname, email As String
Dim phone As Integer
Dim pass, rePass As String

name = TextBox1.Text
surname = TextBox2.Text
email = TextBox3.Text
phone = TextBox4.Text
pass = TextBox5.Text
rePass = TextBox6.Text
Cont…
If pass = rePass Then
accountWriter.WriteLine(name & "," & surname & "," & email & "," & phone &
"," & pass)
Me.Close()
Else
Label7.Text = "Passwords do not match"
TextBox5.Clear()
TextBox6.Clear()
End If
accountWriter.Close()

End Sub
Writing Mark down Files Algorithms:
Bank Statement Generator:
 Declare variable ID to collect the identity number from a text box.
 Use A Stream reader to read bankDetails.txt.
 Declare a variable for the StreamWriter, that sets the second argument to True to create
a new file.
 Declare variables for all the information stored in the bankDetails.txt file.
 Set the text field type and the delimiter.
 Use a while loop to read through the file and set each variable name to a different data
value from the text file.
 Us If statement to search for the ID number in the text file.
 If the ID number is found use the stream writer variable to write the details that are on the
same field as the ID number in different lines in the generated text file.
 Close the stream writer.
EXAMPLE CODE 6
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles
Button1.Click
Dim ID As Integer = TextBox1.Text

Using bank_details As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\


Users\HP\Desktop\Group 5 Presentation\Writing Markdown Files\bankDetails.txt")
Dim bsWriter As IO.StreamWriter = New System.IO.StreamWriter("C:\Users\
HP\Desktop\Group 5 Presentation\Writing Markdown Files\bank_statement.txt", True)

bsWriter.Flush()

Dim currentAcc As String()

Dim ID_num, accNum As Integer

Dim tran1, tran2, tran3, balance As Single


Cont…
bank_details.TextFieldType = FileIO.FieldType.Delimited
bank_details.SetDelimiters(",")
While Not bank_details.EndOfData
currentAcc = bank_details.ReadFields
ID_num = currentAcc(0)
accNum = currentAcc(1)
tran1 = currentAcc(2)
tran2 = currentAcc(3)
tran3 = currentAcc(4)
balance = currentAcc(5)
If Val(ID) = Val(ID_num) Then
bsWriter.WriteLine("Account Number: " & accNum)
bsWriter.WriteLine("Transaction 1: " & tran1)
bsWriter.WriteLine("Transaction 2: " & tran2)
bsWriter.WriteLine("Transaction 3: " & tran3)
bsWriter.Write("Account Balance: " & balance)
End If
End While
bsWriter.Close()
End Using
End Sub
Conclusion
These are the following Key points to remember about File Inputs/outputs
Main points when Reading from a file
Opening of the file
Reading from the file
close the file

When Reading a Delimited File


Must have a My using and End using statement
Must set your delimiter

When Outputting to a File


open the file declaring as a Streamwriter
write to the file
close to the file

You might also like