When a folder need to be read for the content of files, the GetFiles() method is widely used. But it has some negative impacts as well for loading a folder content that has lot of files. To overcome this issue, EnumerateFiles can be used. Look at the following method,
And see why we shouldn't use GetFiles when it comes to large number of files.
The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
Read it here on MSDN
Happy coding... :)
private static string GetFilePathFromDirectory(string path, string fileName)
{
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.EnumerateFiles(fileName))
{
if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())
fi.Name;
}
foreach (FileInfo fi in di.EnumerateFiles(fileName + ".*")) //if the extension doesn't match, find another with same name
{
if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())
fi.Name;
}
return string.Empty;
}
And see why we shouldn't use GetFiles when it comes to large number of files.
The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
Read it here on MSDN
Happy coding... :)