C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: For this method, we receive one path string at a time. EnumerateFiles returns an IEnumerable collection.
And: With a foreach-loop, we can get each string one at a time. If there are many files, this can avoid a large array creation.
IEnumerableForeachC# program that uses EnumerateFiles
using System;
using System.IO;
class Program
{
static void Main()
{
// Returns an IEnumerable<string>.
foreach (string path in Directory.EnumerateFiles("C:\\"))
{
Console.WriteLine(path);
}
}
}
Tip: The Directory.Exists method can be accessed most easily if you add using System.IO to the top of your program.
Tip 2: The method returns a bool: true if the directory is present, and false if it is not.
Bool MethodTrue, FalseC# program that uses Directory.Exists
using System;
using System.IO;
class Program
{
static void Main()
{
if (Directory.Exists("C:\\Users"))
{
Console.WriteLine("Users");
}
if (Directory.Exists("C:\\Losers"))
{
Console.WriteLine("Losers");
}
}
}
Output
Users
Tip: We create DirectoryInfo by passing a directory path to its constructor. DirectoryInfo is a class.
Next: This program gets the name of the directory from DirectoryInfo, and then gets the file count for the directory.
C# program that uses DirectoryInfo
using System;
using System.IO;
class Program
{
static void Main()
{
// Get info.
DirectoryInfo info = new DirectoryInfo(@"C:\Codex\");
// Write name.
Console.WriteLine(info.Name);
// Write file count.
FileInfo[] array = info.GetFiles();
Console.WriteLine(array.Length);
}
}
Output
Codex
5
Version 1: This version of the code uses EnumerateFiles to loop over all the file names in the directory. It does not create an array.
Version 2: This version uses GetFiles, and it creates a local array of string file names.
BenchmarkResult: It is usually acceptable to use GetFiles. The temporary array does not tend to cause many problems.
C# program that times Directory.EnumerateFiles
using System;
using System.Diagnostics;
using System.IO;
class Program
{
const int _max = 1000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use EnumerateFiles.
for (int i = 0; i < _max; i++)
{
foreach (string path in Directory.EnumerateFiles("C:\\"))
{
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use GetFiles.
for (int i = 0; i < _max; i++)
{
string[] paths = Directory.GetFiles("C:\\");
foreach (string path in paths)
{
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
}
}
Output
69516.30 ns EnumerateFiles
69568.30 ns GetFiles
Also: The OpenFileDialog allows users to browse directories and open files, not just other folders.
OpenFileDialogTip: This makes it possible to access the file system only when needed. It makes using a cache of file names more effective.