Directory.GetFiles
What files are in a specific folder? The Directory.GetFiles
function answers this question—it will return an array of all paths in a folder.
Meanwhile, Directory.EnumerateFiles
will do the same thing as Directory.GetFiles
, but will not place them in an array. Instead it just returns the paths one at a time.
GetFiles
exampleThe simplest way to get an array of the files in a location is with Directory.GetFiles
with 1 argument. We must pass it the folder path.
GetFiles()
. The path is relative, and when the path is relative, this is relative to the home directory of the current user.GetFiles
, this is a filter. Each returned path must match the filter format.imports System.IO Module Module1 Sub Main() ' Part 1: get files in relative directory. Dim array1 = Directory.GetFiles("programs/") Console.WriteLine("--- Files: ---") For Each name in array1 Console.WriteLine(name) Next ' Part 2: filter files. Dim array2 = Directory.GetFiles("programs/", "*.TXT") Console.WriteLine("--- TXT Files: ---") For Each name in array2 Console.WriteLine(name) Next End Sub End Module--- Files: --- programs/spellbug ... --- TXT Files: --- programs/search-perls.txt programs/example.txt programs/words.txt
List
It is possible to place the array returned by GetFiles()
into a List
. We can use the ToList
function to get a List
from the array.
imports System.IO Module Module1 Sub Main() ' Get array for absolute directory. Dim array = Directory.GetFiles("/Users/Sam/programs/") ' Convert to list. Dim filesList = array.ToList() Console.WriteLine(filesList.Count) End Sub End Module21
AllDirectories
Sometimes we want to recursively open folders, and then add files from those directories into the result. This can be done with SearchOption.AllDirectories
.
EnumerateFiles
when we want to handle multiple directories, as the resulting file count can be high.imports System.IO Module Module1 Sub Main() ' Use AllDirectories option to recursively traverse folders. For Each file in Directory.EnumerateFiles("programs/", "*.*", SearchOption.AllDirectories) Console.WriteLine("IN DIRECTORY: " + file) Next End Sub End ModuleIN DIRECTORY: programs/rewrite.go ... IN DIRECTORY: programs/vbtest/Program.vb
With Directory.GetFiles
and EnumerateFiles
, we access the file paths within a folder. We can specify a filter string
, or even handle nested directories with SearchOption
.