text file. They include finding if a file exists, opening/creating a
file, reading/writing file, closing file, copying file, deleting file.
You will need a form with two buttons on it. Use the names Step1 and
Step2.
First thing we are going to do is import system.IO. To do this go into
the forms code view. At the very top add this line.
CODE
Imports system.IO
This lets us use the file operations that we need for this tutorial.
Next we need to check to see if a file exists. To do this double click
on the step1 button and type this code.
CODE
If File.Exists("TextFile.txt") then
This line just checks if the file already exists. Next type this line
of code.
CODE
Dim ioFile as new StreamReader("TextFile.txt")
This line of code opens "TextFile.txt" for reading. Now we are going to
read the file and store it into a variable.
CODE
Dim ioLine as string ' Going to hold one line at a time
Dim ioLines as string ' Going to hold whole file
ioLine = ioFile.ReadLine
ioLines = ioLine
While not ioLine = ""
ioLine = ioFile.ReadLine
ioLines = ioLines & vbcrlf & ioLine
End While
We now have the whole text file read into ioLines. Lets display the
text in a message box.
CODE
MsgBox(ioLines)
Now we are going to close the file.
CODE
ioFile.close
Now that we are done reading a file. Lets do the else statement of the
if File.Exists statement. The way this code is going to be set-up is if
the file exists the program reads it. If it doesn't exist it writes a
file.
CODE
Else
Dim ioFile as new StreamWriter("TextFile.txt")
We now have a file open for writting. Lets write two lines to it.
CODE
ioFile.WriteLine("Hi There")
ioFile.WriteLine("User")
So we have some text in the file now. Lets close the file.
CODE
ioFile.Close
We are done with reading/writting files so lets end the if statement
CODE
End If
That is it for that button. Now lets move onto deleteing files. Go back
to form view and double click on the second button. In the code add
these lines.
CODE
If File.Exists("TextFile.txt")
File.Delete("TextFile.txt")
else
msgbox("File doesn't exist")
end if
All this code does is check for the file then if it exists deletes it.
If it doesn't exist then it tells the user that it doesn't exist.
Thats it for this tutorial.
Thanks,
Rich

