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

Recursion using C#

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

Introduction

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.

Background

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
            getDirsFiles(dir);

        }

        //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);
                getDirsFiles(dir);
            }
            
        }

    }
}

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.

History

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

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

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, VB.net, C# and object oriented design using UML.
 
He has Bachelor of Computing with Distinction Grade.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberJimShat21-Mar-13 13:42 
QuestionThanks! PinmemberMember 284527327-Jun-12 4:29 
Questionpar2 and 3 of the article PinmemberDaddi15-Mar-12 2:21 
GeneralMy vote of 4 Pinmemberpeejay027-Mar-12 22:41 
thanks man...good article by the way...
GeneralMy vote of 3 Pinmembertriant26-Jan-12 19:51 
GeneralFile System PinmemberDinesh Girija Sundaram11-Jul-08 0:48 
QuestionPart 2?? PinmemberMarkGMcM16-Sep-07 17:22 
Generalusing io = System.Console; PinmemberDaveMon30-Aug-07 11:15 
Generalplease help a newbe Pinmembermanormi118-Nov-06 15:29 
GeneralHi How to convert the file size to MB or KB Pinmembervivekthangaswamy25-Oct-06 7:46 
GeneralRe: Hi How to convert the file size to MB or KB PinmemberGNIDESIGN2-Feb-10 8:02 
GeneralCool Very good example.. Pinsusscyberiafreak24-Aug-05 2:38 
GeneralRe: Cool Very good example.. PinmemberRahman Mahmoodi24-Aug-05 2:45 
Question"Game programming"? PinsitebuilderUwe Keim16-May-05 21:00 
AnswerRe: "Game programming"? PinmemberRahman Mahmoodi17-May-05 1:57 
GeneralRe: "Game programming"? PinmemberSekGoldenEye16-Aug-07 20: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
Web02 | 2.8.141220.1 | Last Updated 17 May 2005
Article Copyright 2005 by Rahman Mahmoodi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid