Visual Basic Files | Lesson 1
The first thing to learn about files is how to manipulate directories with Visual
Basic.
Type the following at the top of the code page of the form that you have created.
Imports System.IO
By using the Imports statement you will not need to type
System.IO for each command that you will perform on files.
Next you could add a button on the form and double click it. You will use
this button to test some of the routines in this lesson.
Type the following code into the code designer:
Public Function CheckforDirectory(ByVal DirectoryName As String)
As Boolean
Return Directory.Exists(DirectoryName)
End Function
Functions return a value to the calling procedure and subs just process the code
and do not return any value. This function will return a true or false value to
the next routine in this lesson. The boolean data type is a true or false value
and is used extensively in most programs.
The only statement in this function will check if the directory exists or not and
will return the boolean value of true or false to the calling routine.
Next, double click on the Check Directory button and add the following code:
Dim s as string = Me.txbDirectoryName.Text
Try
If Me.CheckforDirectory(s) Then
MessageBox.Show("Directory already exists.")
Else
Directory.CreateDirectory(s)
MessageBox.Show("Directory " & s & "
was created.")
End If
Catch ex As Exception
MessageBox.Show("Cannot check for directory. Reason: " &
ex.Message)
End Try
The first line initializes and sets the variable "s" as a
string(text) and sets its value as the text entered in the textbox txbDirectoryName.
The Try...Catch...End Try block is an error checking function provided with Visual
Basic to check your code for runtime errors. For instance if the variable s is null
then it will throw an error. When it throws an error the code will move to the Catch
statement and display the messagebox. ex is the variable being declared to use in
case an error is caught. This messagebox will show the error message with the part
of the statement: "ex.Message"
The If...Then...End If statement after the Try statement will check if the directory
exists. If it does the program will display the message "Directory already exists."
If the directory does not exist the program will move to the Else statement and
create the directory and then display a messagebox that shows that the directory
was created. To verify this, open up My Computer from the start button and navigate
to the folder that was just created.
Don't be afraid to experiment with this code or any code that is on this site. For
example you can change the variable s to MyDirectoryName or your favorite dog's
name. You can also change the messages that are displayed in each of the messageboxes
to whatever you like. Enjoy and have fun.
Do you have a small business that needs custom software to operate efficiently and at a reasonable price? If so then contact
develop@kalzar.com.