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 example. The 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.
Part 1 We use GetFiles(). The path is relative, and when the path is relative, this is relative to the home directory of the current user.
Part 2 When we pass a second argument to GetFiles, this is a filter. Each returned path must match the filter format.
' Part 1: get files in relative directory.
Dim array1 = Directory.GetFiles("programs/")
Console.WriteLine("--- Files: ---")
For Each name in array1
' Part 2: filter files.
Dim array2 = Directory.GetFiles("programs/", "*.TXT")
Console.WriteLine("--- TXT Files: ---")
For Each name in array2
End Module--- Files: ---
--- TXT Files: ---
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.
' Get array for absolute directory.
Dim array = Directory.GetFiles("/Users/Sam/programs/")
' Convert to list.
Dim filesList = array.ToList()
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.
Tip It is often best to use EnumerateFiles when we want to handle multiple directories, as the resulting file count can be high.
' Use AllDirectories option to recursively traverse folders.
For Each file in Directory.EnumerateFiles("programs/", "*.*", SearchOption.AllDirectories)
Console.WriteLine("IN DIRECTORY: " + file)
End ModuleIN DIRECTORY: programs/rewrite.go
IN DIRECTORY: programs/vbtest/Program.vb
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.