Speed Up File Management With Enumeration

If you’ve ever had manage a collection files in .NET then you know the drill, you call Directory.GetFiles or DirectoryInfo.GetFiles.  In either case you get an array of files back, either in the form of file name strings or FileInfo objects.  This method works just fine for a small list of files, but when the list size starts to get large, loading a large array into memory can be problematic.  Not only does it consume a large amount of memory, but sorting and looping through this large array can be time consuming.

Fortunately, the .NET 4.0 framework added a new method to both the Directory class and DirectoryInfo class called EnumerateFiles.  This method returns an IEnumerable object, which can easily be searched through with LINQ calls.  This new method works faster by not having to stop and wait until an entire array has been allocated for the files.  In addition, FileInfo objects gather all of their necessary data (CreationTime, LastWriteTime, Length, etc) at the time of instantiation when using Enumeration, instead of at the time that each specific property is called (the normal process of the FileInfo object).  This speeds up processing time by making less round trips to the file system and the hard drive.

In addition, like the regular GetFiles method, EnumerateFiles has parameters for Search Patterns and Search Options (All Directories & Top Only).  Also, there is an equivalent method for Directories, with EnumerateDirectories being the method to call instead of EnumerateFiles.

Source:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s