Click here to Skip to main content
Click here to Skip to main content

Class Library for recursing through directories

, 12 Aug 2003
Rate this:
Please Sign up or sign in to vote.
Class Library that recursively searches a given directory and returns an ArrayList of files that can be bound straight to a control.

Screenshot

<!------------------------------- STEP 3 ---------------------------><!-- Add the article text. Please use simple formatting (

,

etc) -->

Introduction

This class library is primarily a utility for a larger application that might need to collate a list of files from a directory. It provides a simple means of returning a collection of files present in a directory, with the option of having the search recurse down all the directories' sub-directories. I've also implemented a way to define a collection of file extensions that filters the collection returned by the search. I wanted this feature so I could define a search that only returned all the *.mp3 files found in a directory.

Basics of the RecursiveFileExplorer Namespace

The very first thing you need is a brief explanation of the RecursiveFileExplorer Namespace and what it contains. Two classes are defined in the namespace:

public class FileExplorer
public class FileData

FileExplorer is the class you would implement to search a directory for files. FileData is the container class used by FileExplorer to store details of the files it finds. To use the RecursiveFileExplorer Namespace, simply include the following at the top of your file.

using RecursiveFileExplorer;

Using the FileExplorer Class

Using the FileExplorer class is deliberately simple. You simply pass it the path to the directory you want to search and it creates a collection of all the files in the directory in the form of an ArrayList object. This ArrayList can then be bound to a data control, or iterated through in some other fashion. The code to do this is as follows:

//Create FileExplorer object and search root directory
FileExplorer FileExplorer = new FileExplorer( "c:/" );
//Access and bind ArrayList to DataSource property of a Data Control
this.ResultsBox.DataSource = FileExplorer.FileList;

Now if you want to get the added functionality of recursing through the sub-directories as well, you need to use one of the other overloaded constructors that takes a boolean value that indicates whether to use recursion. Like so:

//Create FileExplorer object and search root directory
FileExplorer FileExplorer = new FileExplorer( "c:/", true );
//Access and bind ArrayList to DataSource property of a Data Control
this.ResultsBox.DataSource = FileExplorer.FileList;

To apply a filter to the files collated into the collection, use another of the other overloaded constructors that takes an ArrayList of file extensions. Like so:

//Create FileExplorer object and search root directory
ArrayList Extensions = new ArrayList();
Extensions.Add(".mp3");
Extensions.Add(".wav");
FileExplorer FileExplorer = new FileExplorer( "c:/", Extensions );
//Access and bind ArrayList to DataSource property of a Data Control
this.ResultsBox.DataSource = FileExplorer.FileList;

And of course, you can use all three options if you really want to wallow in excess:

//Create FileExplorer object and search root directory
ArrayList Extensions = new ArrayList();
Extensions.Add(".mp3");
Extensions.Add(".wav");
FileExplorer FileExplorer = new FileExplorer( "c:/", Extensions, true );
//Access and bind ArrayList to DataSource property of a Data Control
this.ResultsBox.DataSource = FileExplorer.FileList;

So what's the FileData Class for again...

When the FileExplorer collates the files it finds into a collection it actually stores more than just the fully qualified file name, it also stores the simple filename, the file extension and the length of the file in bytes, and it stores this data in an instance of the FileData class which it then adds to the ArrayList collection. This functionality is provided if you would like to extend the functionality of the class library. For instance I have an extension of this class library that stores ID2 metadata from mp3 files for easy access after the files have been searched through. Okay, so how do you access this information, well it's all pretty simple really:

//Create instance of FileData class by casting an element 
//of the ArrayList collection
FileData FileData = (FileData)FileExplorer.FileList[0];
//Access any members of the FileData object for display to screen
this.DisplayText.Text += "" + FileData.Length;

Code References

The test harness in the source files uses code from the article C# does Shell, Part 1 by Arik Poznanski to implement a dialog to select a folder. You would have thought the .NET Team would have added one in the Core NameSpace's wouldn't you. That would be too easy.

Conclusion

A quick and easy way to gather files from a computer into a collection that can be used in a larger application. The source files contain a class library project and a test harness project in a Visual Studio.NET 2002 solution. I just hope someone besides me can use it to speed up their development.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Andrew Boisen
Software Developer
Australia Australia
No Biography provided

Comments and Discussions

 
GeneralThank you! This saved me *MUCHO* time! Pinmemberdbraseth19-Dec-06 17:32 
GeneralSome error,, need help PinmemberMd Saleem Navalur19-Apr-05 21:12 
GeneralA few enhancements PinmemberD. Emilio Grimaldo Tuñon2-Dec-04 5:35 
GeneralHere is a Strongly Typed FileDataCollection for your project PinmemberJason33312-Sep-04 11:50 
I like your class. I did notice a comment on memory usage problems, and I think those types of issues can be a problem in some cases, but I think if you are using this solution for huge file listings, there is probably a better way to do things. Otherwise, this is a problem free/well done way to do things. I just thought I should make your FileData class have a strongly typed collection. Here it is:
 
using System;
using System.Collections;
 
namespace whatever
{


///
/// Strongly typed collection of FileData.
///

public class FileDataCollection : CollectionBase
{

///
/// Default constructor.
///

public FileDataCollection() :
base()
{
}

///
/// Gets or sets the value of the FileData at a specific position in the FileDataCollection.
///

public FileData this[int index]
{
get
{
return ((FileData)(this.List[index]));
}
set
{
this.List[index] = value;
}
}

///
/// Append a FileData entry to this collection.
///

/// FileData instance.
/// The position into which the new element was inserted.
public int Add(FileData value)
{
return this.List.Add(value);
}

///
/// Determines whether a specified FileData instance is in this collection.
///

/// FileData instance to search for.
/// True if the FileData instance is in the collection; otherwise false.
public bool Contains(FileData value)
{
return this.List.Contains(value);
}

///
/// Retrieve the index a specified FileData instance is in this collection.
///

/// FileData instance to find.
/// The zero-based index of the specified FileData instance. If the object is not found, the return value is -1.
public int IndexOf(FileData value)
{
return this.List.IndexOf(value);
}

///
/// Removes a specified FileData instance from this collection.
///

/// The FileData instance to remove.
public void Remove(FileData value)
{
this.List.Remove(value);
}

///
/// Returns an enumerator that can iterate through the FileData instance.
///

/// An FileData's enumerator.
public new FileDataCollectionEnumerator GetEnumerator()
{
return new FileDataCollectionEnumerator(this);
}

///
/// Insert a FileData instance into this collection at a specified index.
///

/// Zero-based index.
/// The FileData instance to insert.
public void Insert(int index, FileData value)
{
this.List.Insert(index, value);
}

///
/// Strongly typed enumerator of FileData.
///

public class FileDataCollectionEnumerator : object, IEnumerator
{

///
/// Current index
///

private int _index;

///
/// Current element pointed to.
///

private FileData _currentElement;

///
/// Collection to enumerate.
///

private FileDataCollection _collection;

///
/// Default constructor for enumerator.
///

/// Instance of the collection to enumerate.
internal FileDataCollectionEnumerator(FileDataCollection collection)
{
_index = -1;
_collection = collection;
}

///
/// Gets the FileData object in the enumerated FileDataCollection currently indexed by this instance.
///

public FileData Current
{
get
{
if (((_index == -1)
|| (_index >= _collection.Count)))
{
throw new System.IndexOutOfRangeException("Enumerator not started.");
}
else
{
return _currentElement;
}
}
}

///
/// Gets the current element in the collection.
///

object IEnumerator.Current
{
get
{
if (((_index == -1)
|| (_index >= _collection.Count)))
{
throw new System.IndexOutOfRangeException("Enumerator not started.");
}
else
{
return _currentElement;
}
}
}

///
/// Reset the cursor, so it points to the beginning of the enumerator.
///

public void Reset()
{
_index = -1;
_currentElement = null;
}

///
/// Advances the enumerator to the next queue of the enumeration, if one is currently available.
///

/// true, if the enumerator was succesfully advanced to the next queue; false, if the enumerator has reached the end of the enumeration.
public bool MoveNext()
{
if ((_index
< (_collection.Count - 1)))
{
_index = (_index + 1);
_currentElement = this._collection[_index];
return true;
}
_index = _collection.Count;
return false;
}
}
}
}
 

Then all you have to do is change your File explorer methods to use this:
 
FileDataCollection List = new FileDataCollection();
 
Instead of this:
ArrayList List = new ArrayList();
 
Have Fun!
GeneralNice but ... PinmemberSébastien Lorion16-Aug-03 5:50 
GeneralRe: Nice but ... PinmemberJason Webb24-Apr-05 22:37 
GeneralI was looking for something like this... PinmemberBrandon Haase14-Aug-03 7:45 
GeneralNice PinmemberSteve McLenithan14-Aug-03 4:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150301.1 | Last Updated 13 Aug 2003
Article Copyright 2003 by Andrew Boisen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid