Visual Basic Tutorials and Code


Creating and deleting directories

The most importand commands that we use in this tutorial are 'MkDir' and 'RmDir', that is 'make a directory' and 'remove a directory'.
For enhancing the program, we use a while loop to create several directories following a pattern.


First, download the code from here.


You probably already know the Visual Basic loops and other elementary things about Visual Basic, so I'm not going to insist on analyzing the small code.

The main action takes place when we click the cmdMakeDir button:



Dim i As Integer
i = 1
While i <= txtNum.Text
Dim dir As String
dir = txtPath.Text & i
MkDir dir
i = i + 1
Wend




Dim i As Integer
i = 1

We create a variable i that will be used for looping.





While i <= txtNum.Text

We test to see if i is smaller than number typed in the txtNum that shows us how many directories we want to create.





Dim dir As String
dir = txtPath.Text & i

We concatenate the string in txtPath.Text (the path where we want the directories to be created) with the number that the variable i currently holds.


Warning: Be sure the directory where you want the other directories to be created exists, else you will get an ugly error.


Here is the trick:
We suppose we have a directory named temp in the root of C:\ (C:\temp).
If in the txtPath we type C:\temp\ (notice the trailing slash), we will have directories 1, 2, 3... (till we reach the number typed in the txtNum) created in the folder C:\temp.
The path for the directories will be:

C:\temp\1
C:\temp\2
C:\temp\3

... and so on.

On the other hand, if we type C:\temp (notice there is no trailing slash), we will have the directories created in the root of C:\ with the prefix 'temp', like this:

C:\temp1
C:\temp2
C:\temp3

... and so on.
This is because when we concatenate using:


dir = txtPath.Text & i

we actually have dir = C:\temp1 because we didn't add the trailing slash.





MkDir dir

Then we create the actually directory...


i = i + 1

Increment the variable so the loop isn't endless...


Wend

And close the loop.

This is a basic way to create several folders using a prefix. From now on it's easy to create directories using a prefix or a suffix, or both. Or following a pattern.




Written by