Home and Learn: VB Net Course
In this lesson, we'll take a look at some file and folder operations you can do with VB NET. First, we'll see how to get all the files from a particular folder. If you want to know how to get all the folders and files from sub folders, scroll down to the bottom.
Start a new project and add a button and a listbox to your form. Double-click your button to create a code stub.
You can use an Open File Dialog control to get the name of a folder, which we did in an earlier lesson. This time, however, we'll just hard code it. Add this line to your button:
Dim PathToFolder As String = "C:\Users\Ken\Documents\ 1_MyFolder\"
Obviously, you should change the path name to point to a folder on your own computer.
Now add this line:
Dim files As String() = IO.Directory.GetFiles(PathToFolder)
The inbuilt class we need is called Directory. The Directory class has a function called GetFiles. Not surprisingly, it gets all the files from a folder when you give it a file path. You give it a path by adding a file path between the round brackets. One thing to note here is that we have another pair of round brackets after As String. This creates a String array. The name of the array is files. All the files that VB Net finds in the specified folder will be placed in this files array.
You can use a For Each loop to get each file from the files array. Add this:
For Each filePath In files
ListBox1.Items.Add(filePath)
Next
Of course, once you get the file path, you'd want to do something useful with it, like opening the file the path points to. We did this in a previous lesson, so won't repeat the code. Here, we're just adding the filepath to our listbox.
Test it out. Run your form and click your button. In the listbox, you should see the full file path of each file in your designated folder.
Sometimes, you just need the file name and not the full file path.
Add a new listbox to your form. In your button code, add this new For Each loop:
For Each fileName In files
ListBox2.Items.Add( IO.Path.GetFileName(fileName) )
Next
Here's the bit that does the work:
IO.Path.GetFileName(fileName)
The code uses the inbuilt class, Path. The Path class has a function called GetFileName. In between the round brackets of GetFileName, you provide a file path. Ours is in the filename variable, which we get from the For Each loop.
Run your code and test it out. When you click your button, you should see just the file names appearing in your new listbox, rather than the full file path and file name, which we have in listbox1.
If you need to get just the type of file, there is a function you can use of the Path class called GetExtension.
Add a new listbox to your form. In your button code, add this new For Each loop:
For Each fileExtension In files
ListBox3.Items.Add( IO.Path.GetExtension(fileExtension) )
Next
This is the line that does the work:
IO.Path.GetExtension(fileExtension)
We're sure you can work out what it does! One thing to note, however, is that GetExtension includes the dot before the letters. So, .html and not just html.
Again, run your code and click the button. All the file extensions from
your designated folder should appear in your new listbox.
The Path class also has a function called GetRandomFileName. You can use this to generate a random file name 8 letters long. Here's some code to try (add a new listbox):
For i = 0 To 9
Dim ranFileName As String = IO.Path.GetRandomFileName()
ListBox4.Items.Add(ranFileName)
Next
The code generates 10 random file names. However, it also generates random file extensions. So you end up with this sort of thing:
dq2ucst2.mxo
4dqasw4g.kmx
vzuuucr2.gr4
If you want to add a real file extension, you have add the extension yourself. Change your code to this:
For i = 0 To 9
Dim ranFileName As String = IO.Path.GetRandomFileName()
Dim filename As String = IO.Path.GetFileNameWithoutExtension(ranFileName)
Dim addRealExtension As String = filename & ".txt"
ListBox4.Items.Add(addRealExtension)
Next
The new code uses the GetFileNameWithoutExtension function of the Path class:
IO.Path.GetFileNameWithoutExtension(ranFileName)
In between the round brackets of GetFileNameWithoutExtension, you need that random file name you generated. VB Net will then strip off the file extension, including the dot.
The other new line just adds the file extension .txt. So we're generating 10 random file names of type txt. In a previous section, you saw how to write to a file. You could use these random file names to create as many blank text files as you wanted.
A folder might contain other folders and files. If you want to get all the files and folders in a directory, the code is a little trickier, as you have to use recursion. Let's see how it works.
Add a new button to your form for this, as well as a new listbox.
As the code for the button, add these two lines (change the path to point to a folder on your own computer):
Dim PathToFolder As String = "C:\Users\Ken\Documents\1_MyFolder\"
GetFilesAndFolders(PathToFolder)
You'll get an error for the GetFilesAndFolders line. That's because we haven't written this Subroutine yet.
Add the Sub now:
Private Sub GetFilesAndFolders(folder_name)
End Sub
As the first few lines of the Sub, add these:
ListBox1.Items.Add("===================")
ListBox1.Items.Add("FOLDER:" & folder_name)
ListBox1.Items.Add("===================")
We're just adding a heading here, so we can see which folder we're in. The lines don't do anything useful. You could miss them out entirely, if you wanted to.
To get all the files in each folder, add this For Each Loop:
For Each singleFile In IO.Directory.GetFiles(folder_name)
ListBox1.Items.Add( Path.GetFileName(singleFile) )
Next
We've already done this in code above. We're just listing the file names in a folder.
Now we can search for every folder in the directory. Add this For Each loop:
For Each folder In IO.Directory.GetDirectories(folder_name)
GetFilesAndFolders(folder)
Next
Your Sub should look like this:
We're now using the function GetDirectories, which is in the Directory class. As its name suggest, you can use this function to get folders inside of another folder.
The line that ensures that each folder is searched is this one:
GetFilesAndFolders(folder)
This is recursion. What this means is that the GetFileAndFolders Sub will get called over and over again until no more folders are left to grab. Each time we call the GetFileAndFolders Sub, all of its code gets executed, including those header lines, and the For Each loop that gets the file names from the folder.
Recursion can be tricky to follow. But study the code and you'll get there.
But run your program again. Click your new button and you should see something like this appear in your listbox1:
As you can see, our code has searched all the folders in our root folder, 1_MyFolder. It found 5 other folders, and it has listed all the files in each folder.
You might want to be careful with this code. If you point it at the wrong directory, you could be there all night waiting for it to finish listing all the folders and files!
In the next lesson, we'll move on and tackle Events in VB Net.
Learn about Events in VB .NET -->
Back to the VB NET Contents Page
Email us: enquiry at homeandlearn.co.uk