Click here to Skip to main content
12,505,655 members (55,352 online)
Click here to Skip to main content
Add your own
alternative version

Stats

71.3K views
507 downloads
59 bookmarked
Posted

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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralThank you! This saved me *MUCHO* time! Pin
dbraseth19-Dec-06 16:32
memberdbraseth19-Dec-06 16:32 
GeneralSome error,, need help Pin
Md Saleem Navalur19-Apr-05 20:12
memberMd Saleem Navalur19-Apr-05 20:12 
GeneralA few enhancements Pin
D. Emilio Grimaldo Tuñon2-Dec-04 4:35
memberD. Emilio Grimaldo Tuñon2-Dec-04 4:35 
GeneralHere is a Strongly Typed FileDataCollection for your project Pin
Jason33312-Sep-04 10:50
memberJason33312-Sep-04 10: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
{


///
public class FileDataCollection : CollectionBase
{

///
public FileDataCollection() :
base()
{
}

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

///
/// FileData instance.
///
public int Add(FileData value)
{
return this.List.Add(value);
}

///
/// FileData instance to search for.
///
public bool Contains(FileData value)
{
return this.List.Contains(value);
}

///
/// FileData instance to find.
///
public int IndexOf(FileData value)
{
return this.List.IndexOf(value);
}

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

///
///
public new FileDataCollectionEnumerator GetEnumerator()
{
return new FileDataCollectionEnumerator(this);
}

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

///
public class FileDataCollectionEnumerator : object, IEnumerator
{

///
private int _index;

///
private FileData _currentElement;

///
private FileDataCollection _collection;

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

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

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

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

///
///
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 ... Pin
Sébastien Lorion16-Aug-03 4:50
memberSébastien Lorion16-Aug-03 4:50 
GeneralRe: Nice but ... Pin
Jason Webb24-Apr-05 21:37
memberJason Webb24-Apr-05 21:37 
GeneralI was looking for something like this... Pin
Brandon Haase14-Aug-03 6:45
memberBrandon Haase14-Aug-03 6:45 
GeneralNice Pin
Steve McLenithan14-Aug-03 3:26
memberSteve McLenithan14-Aug-03 3:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web02 | 2.8.160927.1 | Last Updated 13 Aug 2003
Article Copyright 2003 by Andrew Boisen
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid