Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between EnumerateFiles and EnumerateFileSystemEntries in .NET 4?

Tags:

In .Net 4 there are two functions to enumerate files in a path. The EnumerateFiles and EnumerateFileSystemEntries. The MSDN does not give enough explanations about their differences. Which are these differences?

like image 822
Dragno Avatar asked Nov 19 '12 10:11

Dragno


3 Answers

EnumerateFileSystemEntries => enumerate files, directories, and both files and directories.

EnumerateFiles => for enumarting only files. (Not directories)

like image 77
Habib Avatar answered Oct 09 '22 12:10

Habib


EnumerateFiles returns only file names. EnumerateFileSystemEntries returns names of directories also

like image 30
Sergey Berezovskiy Avatar answered Oct 09 '22 11:10

Sergey Berezovskiy


As @Habib and @Sergey answered, you need to use EnumerateFileSystemEntries instead of EnumerateFiles. I will extend their answers with an example.

  • EnumerateFiles: Returns an enumerable collection of file names that match a search pattern in a specified path, and optionally searches subdirectories.
  • EnumerateFileSystemEntries: returns an enumerable collection of file names and directory names in a specified path.

Here is a code to showcase the difference:

public static void Main()
{
    Directory.CreateDirectory("dir");
    Directory.CreateDirectory("dir2");
    File.WriteAllText(Path.Combine("dir", Path.GetRandomFileName()), "file");
    var datapath = ".";

    var files = Directory.EnumerateFiles(datapath, "*", SearchOption.AllDirectories);
    files.Dump();

    var fileSystemEntries  = Directory.EnumerateFileSystemEntries(datapath, "*", SearchOption.AllDirectories);
    fileSystemEntries.Dump();
}

output

Dumping object(System.IO.FileSystemEnumerableIterator`1[String])
[
   .\dir\epp3114y.jjr
]
Dumping object(System.IO.FileSystemEnumerableIterator`1[String])
[
   .\dir
   ,
   .\dir2
   ,
   .\dir\epp3114y.jjr
]

Try it Online!

like image 26
aloisdg Avatar answered Oct 09 '22 12:10

aloisdg