Click here to Skip to main content
11,704,768 members (49,783 online)
Click here to Skip to main content

Recursion using C#

, 16 May 2005 150.3K 1.2K 41
Rate this:
Please Sign up or sign in to vote.
Background, advantage and usage of Recursion in C#.


The article explains the background and usage of recursion in C#. It illustrates the usage of recursion to iterate though the file system in a specified folder / drive. Most beginners in programming are confused with the usage of recursion and therefore here I am trying to explain it in an easy way with a simple usable code. The advantage of this code snippet is that it can be used in any other project if the users are dealing with file system. In part 2 and 3, I will explain how to extend the same code to write the output in a file and read from it, and also how to search the file based on specific criteria.


Before I explain how to use recursion in C#, it's really important to give some background information about recursion and why it's important.

What is recursion?

Basically, in simple terms, recursion is a function that calls itself iteratively until it reaches a stopping point. In another words, recursion is a common method of simplification to divide a problem into sub-problems of the same type. As a computer programming technique, this is called "divide and conquer" and is key to the design of many important algorithms particularly in Arterial Intelligence programming.

The file system is a very good example of recursive programming. Let us say we want to iterate through all the files in all the folders under C:\Program Files\Adobe\Acrobat 5.0 folder as in the above image, the following definition is correct:

ENU has some files and has a parent folder which is HELP. Similarly, HELP has some files and has a parent folder which is Acrobat 5.0 and so on until it reaches the target folder of C:\Program Files\Adobe\Acrobat 5.0. And it could be correct the other way around, i.e. C:\Program Files\Adobe\Acrobat 5.0 has some files and a child folder, Acrobat 5.0 has some files and a child folder until it reaches the final child ENU.

Therefore, if we write down the code to iterate though one of these folders and its files and call it repeatedly, then we have solved the problem. In other words, we are dividing the Bigger Problem of iterating through the Adobe folder to sub-problems which is just iterating through a single folder and calling it iteratively and the problem is resolved.

How recursion works?

Basically it is defining a problem in the form of itself and calling it repeatedly. However the important point to notice is that there should be a Stopping Point or 'End Condition'.

Advantages of recursion:

  • Game programming
  • Artificial Intelligence
  • Most of the mathematic functions can be presented in the form of recursion
  • For some problems, it very easy to understand them using recursion

Enough of the theory. Now let us have a look at some actual C# code.

Using the code

namespace Recursion
    class IterateFolders
        public    static void Main(string[] args)
            //Create a Directory object using DirectoryInfo 
            DirectoryInfo dir = 
               new DirectoryInfo(@"C:\Program Files\Adobe\Acrobat 5.0");
            //Pass the Directory for displaying the contents


        //this is the recursive function
        public static void getDirsFiles(DirectoryInfo d)
            //create an array of files using FileInfo object
            FileInfo [] files;
            //get all files for the current directory
            files = d.GetFiles("*.*");

            //iterate through the directory and print the files
            foreach (FileInfo file in files)
                //get details of each file using file object
                String fileName = file.FullName;
                String fileSize = file.Length.ToString();
                String fileExtension =file.Extension;
                String fileCreated = file.LastWriteTime.ToString();

                io.WriteLine(fileName + " " + fileSize + 
                   " " + fileExtension + " " + fileCreated);
            //get sub-folders for the current directory
            DirectoryInfo [] dirs = d.GetDirectories("*.*");
            //This is the code that calls 
            //the getDirsFiles (calls itself recursively)
            //This is also the stopping point 
            //(End Condition) for this recursion function 
            //as it loops through until 
            //reaches the child folder and then stops.
            foreach (DirectoryInfo dir in dirs)
                io.WriteLine("--------->> {0} ", dir.Name);


The output will show all folders for the specified folder and list the details of each file including full path, size, extension and date created.

Points of Interest

This is the Part 1 of the 3 part series tutorial about recursion and the file system. Part 2 will show how to extend the same code to save the output of this program in a text file and then read from it. And finally in Part 3, I will extend the functionality to search a text file based on specific criteria and find files. By a bit more effort the same code can be used to write a CD / DVD Catalogue utility which can catalogue CDs/DVDs and then search through the code for specific files.


Part I of a three part series, posted on Sat 14th May 2005.


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


About the Author

Rahman Mahmoodi
Software Developer
Australia Australia
Rahman has worked in different areas of Software System Development Life Cycle. He started working as Tester and then moved to application programming and web application programming.

At the moment his area of interest are .Net including ASP.Net/2,, C# and object oriented design using UML.

He has Bachelor of Computing with Distinction Grade.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
JimShat21-Mar-13 12:42
memberJimShat21-Mar-13 12:42 
QuestionThanks! Pin
Member 284527327-Jun-12 3:29
memberMember 284527327-Jun-12 3:29 
Questionpar2 and 3 of the article Pin
Daddi15-Mar-12 1:21
memberDaddi15-Mar-12 1:21 
GeneralMy vote of 4 Pin
peejay027-Mar-12 21:41
memberpeejay027-Mar-12 21:41 
GeneralMy vote of 3 Pin
triant26-Jan-12 18:51
membertriant26-Jan-12 18:51 
GeneralFile System Pin
Dinesh Girija Sundaram10-Jul-08 23:48
memberDinesh Girija Sundaram10-Jul-08 23:48 
QuestionPart 2?? Pin
MarkGMcM16-Sep-07 16:22
memberMarkGMcM16-Sep-07 16:22 
Generalusing io = System.Console; Pin
DaveMon30-Aug-07 10:15
memberDaveMon30-Aug-07 10:15 
Generalplease help a newbe Pin
manormi118-Nov-06 14:29
membermanormi118-Nov-06 14:29 
Hi I really like this example but want to use it in a .net web app to display the file structure of my website in a web page, could you please tell me how I can bind the results to a webpage for displaying?
thanks Mark
GeneralHi How to convert the file size to MB or KB Pin
vivekthangaswamy25-Oct-06 6:46
membervivekthangaswamy25-Oct-06 6:46 
GeneralRe: Hi How to convert the file size to MB or KB Pin
GNIDESIGN2-Feb-10 7:02
memberGNIDESIGN2-Feb-10 7:02 
GeneralCool Very good example.. Pin
cyberiafreak24-Aug-05 1:38
susscyberiafreak24-Aug-05 1:38 
GeneralRe: Cool Very good example.. Pin
Rahman Mahmoodi24-Aug-05 1:45
memberRahman Mahmoodi24-Aug-05 1:45 
Question"Game programming"? Pin
Uwe Keim16-May-05 20:00
sitebuilderUwe Keim16-May-05 20:00 
AnswerRe: "Game programming"? Pin
Rahman Mahmoodi17-May-05 0:57
memberRahman Mahmoodi17-May-05 0:57 
GeneralRe: "Game programming"? Pin
SekGoldenEye16-Aug-07 19:32
memberSekGoldenEye16-Aug-07 19:32 

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
Web01 | 2.8.150819.1 | Last Updated 17 May 2005
Article Copyright 2005 by Rahman Mahmoodi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid