• Home
  • About

Snippet IT

IT News, Programming, Internet and Blogging

  • Programming and Scripting
  • Tips and Tricks
  • Software and Hardware
  • New and Happening
You are here: Home / Programming and Scripting / C# – Loop all files in directory and it’s sub-directories

C# – Loop all files in directory and it’s sub-directories

February 7, 2009 by Sze Hau 5 Comments

Recently I need to write some code to read all files in a directory and it’s sub-directories. There are simple way and difficult way (Not very difficult actually). The simple way will be writing a function that reads all files in the directory and call the function again recursively for each sub-directory in that directory.

Although it is simple but it is not efficient, especially when running on a small computer (e.g. handheld device), it can use up a lot of call stack space when the recursion is too deep. Besides it is very hard to debug or extend the functionality in case of recursive logic.

Here is the recursion version of looping all files in the directory and it’s sub-directories:

void ProcessFiles(string path)
{
    string[] files;
    string[] directories;

    files = Directory.GetFiles(path);
    foreach(string file in files)
    {
        // Process each file
    }

    directories = Directory.GetDirectories(path);
    foreach(string directory in directories)
    {
        // Process each directory recursively
        ProcessFiles(directory);
    }
}

Instead of using the recursion way of looping all the files in directory and it’s sub-directories, we can change it to iteration way by introduce a stack instance. The iteration way of doing this task is much more efficient. The iteration way will be writing a function that loop all the directory stored in the stack instance. In each loop, files are processed and when more directories are discovered, simply push the directory into the stack instance.

Here is the ieteration version of looping all files in the directory and it’s sub-directories:

void ProcessFiles(string path)
{
    Stack<string> stack;
    string[] files;
    string[] directories;
    string dir;

    stack = new Stack();
    stack.Push(path);

    while (stack.Count > 0) {

        // Pop a directory
        dir = stack.Pop();

        files = Directory.GetFiles(dir);
        foreach(string file in files)
        {
            // Process each file
        }

        directories = Directory.GetDirectories(dir);
        foreach(string directory in directories)
        {
            // Push each directory into stack
            stack.Push(directory);
        }
    }
}

Note: The codes above do not catch any exception. It is always good practice to catch and handle all possible exceptions throwing from functions (e.g. Permission exception of reading files and e.t.c.)

More from my site

  • Java: How To Implement ungetc in JavaJava: How To Implement ungetc in Java
  • C#: Unix Time to .Net DateTime and Vice VersaC#: Unix Time to .Net DateTime and Vice Versa
  • Google Chromium OSGoogle Chromium OS
  • Java: Least Recently Used (LRU) CacheJava: Least Recently Used (LRU) Cache
  • Java: Continuously Read Data From FileChannel Without MappedByteBufferJava: Continuously Read Data From FileChannel Without MappedByteBuffer
  • Unix Shell Script: How to Receive Input Right After Echoing A LineUnix Shell Script: How to Receive Input Right After Echoing A Line

Filed Under: Programming and Scripting, Tips and Tricks Tagged With: C#, iteration, recursion

About Sze Hau

Geek. Love programming. Coffee addicted. Married with two children. Working towards financial freedom.

Comments

  1. marco says

    April 22, 2009 at 5:01 am

    good evening,
    you have two errors in the code

    faux : dir = stack.Pop();
    Vrai : dir = (string)stack.pop();
    And
    faux : directories = Directory.GetDirectories(path);
    vrai : directories = Directory.GetDirectories(dir);

    thank you very much for this code
    marc

  2. szehau says

    April 22, 2009 at 12:16 pm

    For the first statement, my original code should declare stack as a string stack Stack<string>. I have fixed that now.

    For the second statement, you are right. I have fixed that too. My mistake 🙂

    Thanks.

  3. Scott Leckie says

    March 14, 2010 at 8:26 am

    I like (and use) this technique. The only things I would add are that, in a real world environment there are a couple of pseudo-expected exceptions that you may hit; UnauthorizedAccessException and PathTooLongException). My sample code pretty much mimics yours but also takes into account these “acceptable exceptions”. Please have a look at http://www.scottleckie.com/2009/07/iterating-through-a-bunch-of-folders-and-files/

    Cheers
    Scott

  4. szehau says

    March 14, 2010 at 11:07 am

    Yes, my sample doesn’t handle any “acceptable exception” because I think it depends on what you application need. Some may just simply want to skip the file for certain exceptions and some may want to stop the application for all exceptions.

  5. Scott Leckie says

    March 14, 2010 at 7:20 pm

    Indeed. It wasn’t a criticism, just a fact of life if the app will be used by lots of different users to look at a remote file system, and they don’t necessarily have rights to the entire structure.

    Regards
    Scott

Leave a Reply Cancel reply

Advertisement

  • Facebook
  • Google+
  • Instagram
  • Twitter

Email News Letter

Sign up to receive updates daily and to hear what's going on with us

Software and Hardware

MD5 and SHA1 Checksum Using Windows

July 5, 2017 By Sze Hau Leave a Comment

Blog Network

  • Personal Fincance Personal Finance – Personal Money Tips, Stock Investment, Small Business and Make Money Online
  • szehau's weblog Life, Internet, Software, Gadgets, Programming and Investments

Snippet IT

This is the place where I want to share anything about information technology.

Search

Recent

  • MD5 and SHA1 Checksum Using Windows
  • MD5 and SHA1 Checksum Using Linux
  • Java: Unlimited Strength Jurisdiction Policy
  • WordPress: How To Change Admin Username
  • Linux: How To Compress And Decompress Folders And Files

Tags

Adsense advertisement advertising apache blog blogging tips C# EGPC error estimation format format Integer Gmail Google Google Adsense Google Chrome Google Search Engine Google search result how to HTTP internet marketing Java JavaScript Linux money password performance PHP programming search engine optimization secure security short URL SQL static constructor String tiny URL Tips and Tricks twitter video Windows Vista Wordpress wordpress plugin wordpress theme Youtube

Copyright © 2025 · Magazine Pro Theme on Genesis Framework · WordPress · Log in