Mettu University
Event driven programming ITec3053
Chapter 5- Manipulating Files
19-12-2016
Outline
o Manipulating Files
o How to open a Text File
o Read a file line by line in VB .NET
o Write to a Text File
o How to Copy, Move and Delete a File
19-12-2016
Manipulating Files
o A file is a collection of data stored in a disk with a specific name and a
directory path.
o When a file is opened for reading or writing, it becomes a stream.
o The stream is basically the sequence of bytes passing through the
communication path.
o There are two main streams: the input stream and the output stream.
o The input stream is used for reading data from file readoperation and
the output stream is used for writing into the file writeoperation.
[Link] I/O Classes
o The [Link] namespace has various classes that are used for
performing various operations with files, like creating and deleting files,
reading from or writing to a file, closing a file, etc.
o The following table shows some commonly used non-abstract classes in
the [Link] namespace:
19-12-2016
I/O (input output) Class Description
BinaryReader Reads primitive data from a binary stream.
BinaryWriter Writes primitive data in binary format.
BufferedStream A temporary storage for a stream of bytes.
Directory Helps in manipulating a directory structure.
File Helps in manipulating files
FileInfo Used for performing operations on files.
FileStream Used to read from and write to any location in a file.
Path Performs operations on path information.
StreamReader Used for reading characters from a byte stream.
StreamWriter Is used for writing characters to a stream.
DirectoryInfo Used for performing operations on directories.
19-12-2016
The FileStream Class
o The FileStream class in the [Link] namespace helps in reading
from, writing to and closing files.
o This class derives from the abstract class Stream.
o You need to create a FileStream object to create a new file or open an
existing file.
o The syntax for creating a FileStream object is as follows:
o Dim <object_nam e> As FileStream = New FileStream (<file_nam e>,
<FileMode Enum erator>,<FileAccess Enumerator>, <FileShare Enum
erator>)
o Example:
For creating a FileStream object F1 for reading a file named [Link]:
Dim f1 As FileStream = New FileStream ("[Link]", [Link],
[Link])
19-12-2016
The FileStream Class…
o FileMode: The FileMode enumerator defines various methods for
opening files.
o The members of the FileMode enumerator are:
parameter Description
FileMode: Append: It opens an existing file and puts cursor at the end of file, or creates
the file, if the file does not exist.
Create: It creates a new file.
CreateNew: It specifies to the operating system that it should create a new file.
Open: It opens an existing file.
OpenOrCreate: It specifies to the operating system that it should open a file if
it exists, otherwise it should create a new file.
Truncate: It opens an existing file and truncates its size to zero bytes.
19-12-2016
The FileStream Class…
o FileAccess: FileAccess enumerators have members: Read, ReadWrite and
Write.
o FileShare:FileShare enumerators have the following members:
parameter Description
FileShare: Inheritable: It allows a file handle to pass inheritance to the child processes.
None: It declines sharing of the current file
Read: It allows opening the file for reading
ReadWrite: It allows opening the file for reading and writing
Write: It allows opening the file for writing
19-12-2016
Text Files and VB .NET
o There is a very useful object in [Link] called System.
o IO (the IO stands for Input and Output).
o You can use this object to read and write to text files.
How to Open a Text File in VB .NET
o To open up a text file, you need to create something called a
"StreamReader".
o This, as its name suggests, reads streams of text.
o The StreamReader is an object available to [Link].
o You create a StreamReader like this:
Dim FILE_NAME As String = "C:\[Link]"
Dim objReader As [Link]
objReader = New [Link](FILE_NAME)
19-12-2016
Read To End
o But this won't do you any good. We haven't actually opened
the text file yet. We've just told VB where the text file is and
what object to open it with.
o You do the opening like this:
[Link] = [Link]
o Now that objReader is an object variable, it has its own
properties and methods available for use (in the same way
that the textbox has a Text property).
o One of the Methods available to our new StreamReader
variable is the ReadToEnd method.
o This will read the whole of your text, right to the end.
19-12-2016
Read To End…
Steps:
oStart a new project
oAdd a textbox to your new form, and just leave it on the default Name of
Textbox1
oSet its MultiLine property to True
oAdd a Button to your form. Set the Text property of the button to “Read
from File".
oDouble click the button and add the following code for it:
Dim FILE_NAME As String = "C:\[Link]"
Dim objReader As New [Link](FILE_NAME)
[Link] = [Link]
[Link]()
oWhat happens if the file does not exist??
19-12-2016
Read To End…
o You can, though, test to see if the file exists.
o If it does, you can open it; if not, you can display an error message.
o Amend your code to this (the new lines are in bold, red):
Dim FILE_NAME As String = "C:\[Link]"
If [Link](FILE_NAME) = True Then
Dim objReader As New
[Link](FILE_NAME)
[Link] = [Link]
[Link]()
Else
MsgBox("File Does Not Exist")
End If
19-12-2016
Read a file line by line in VB .NET
o Quite often, you don't want to read the whole file at once.
You want to read it line by line. In which case, instead of
using the ReadToEnd method, you can use the ReadLine
method:
o The ReadLine method, as its name suggests, reads text one
line at a time.
o In order to do this, though, you need to use a loop. You can
then loop round each line and read it into a variable.
19-12-2016
o Here's a coding example:
Dim FILE_NAME As String = "C:\[Link]"
Dim TextLine As String
If [Link](FILE_NAME) = True Then
Dim objReader As New
[Link](FILE_NAME)
Do While [Link]() <> -1
TextLine = TextLine & [Link]() &
vbNewLine
Loop
[Link] = TextLine
Else
MsgBox("File Does Not Exist")
End If
19-12-2016
How to Write to a Text File in VB .NET
o Instead of using the StreamReader we use the StreamWriter.
o The StreamWriter is used to write a stream of text to a file.
o Add another Button to the form you've been working on. Set the Text property of
the button to "Write to File". Double click your new button to open up the coding
window. Add the following:
Dim FILE_NAME As String = "C:\[Link]"
If [Link](FILE_NAME) = True Then
Dim objWriter As New [Link](FILE_NAME)
[Link]([Link])
[Link]()
MsgBox("Text written to file")
Else
MsgBox("File Does Not Exist")
End If
19-12-2016
How to Write to a Text File in VB .NET…
o If you don't have to write the whole text at once, you can write line by line.
o In that case, select WriteLine (instead of Write) from the available
properties and methods.
o Here's an example of how to use WriteLine:
Dim FILE_NAME As String = "C:\[Link]"
Dim i As Integer
Dim aryText(4) As String
aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "A"
aryText(3) = "Little"
aryText(4) = "One"
Dim objWriter As New [Link](FILE_NAME)
For i = 0 To 4
[Link](aryText(i))
Next
[Link]()
19-12-2016
Appending Text to a File in VB .NET
o There will be times when you won't want to erase all the
text from your file.
o You'll only want to add text to what you currently have. In
which case you need to Append.
o To append text to a file, you type a comma after your file
name then type the word True:
Dim objWriter As New
[Link](FILE_NAME, True)
19-12-2016
Appending Text to a File in VB .NET…
Dim FILE_NAME As String = "C:\[Link]"
Dim i As Integer
Dim aryText(4) As String
aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "Another"
aryText(3) = "Little"
aryText(4) = "One"
Dim objWriter As New [Link](FILE_NAME,
True)
For i = 0 To 4
[Link](aryText(i))
Next
[Link]()
MsgBox("Text Appended to the File")
19-12-2016
How to Copy a File in VB .NET
o You can also copy a file that you've created. This time, we don't
need the StreamWriter or StreamReader of [Link]. We need
the File object:
[Link]
o File has it's own properties and methods you can use. One of
these is Copy. Here's some code that makes a copy of our test file
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = "C:\[Link]"
NewCopy = "C:\[Link]"
If [Link](FileToCopy) = True Then
[Link](FileToCopy, NewCopy)
MsgBox("File Copied")
End If
19-12-2016
How to Move a File with VB .NET
o This time, we use the Move method of [Link].
o Here's some code:
FileToMove = "C:\[Link]"
MoveLocation = "C:\ technology\[Link]"
If [Link](FileToMove) = True Then
[Link](FileToMove,
MoveLocation)
MsgBox("File Moved")
End If
19-12-2016
How to Delete a File in VB .NET
o To delete a file from your computer, you use the Delete
method of [Link].
o Here's some new code for you to try:
Dim FileToDelete As String
FileToDelete = "C:\[Link]"
If [Link](FileToDelete) = True Then
[Link](FileToDelete)
MsgBox("File Deleted")
End If
19-12-2016