Sunday, January 18, 2009

C#: List all the files from dir and sub dir

This code shows how to list all the files from dir and sub dir



// all the Namespace is not mandatory, when you use VS 2008, by default first 4 namespace will appear,
// System.IO is mandatory for our functionality

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

///
/// Use this method to explore a directory and all of its files. Then, it
/// recurses into the next level of directories, and collects a listing
/// of all the file names you want.
///


static class FileSystemUtil{
///
/// Find all files in a directory, and all files within every nested
/// directory.
///


/// The starting directory you want to use.
/// A string array containing all the file names.

static public string[] GetAllFileNames(string baseDir)
{
//
// Store results in the file results list.
//

List fileResults = new List();
//
// Store a stack of our directories.
//

Stack directoryStack = new Stack();
directoryStack.Push(baseDir);
//
// While there are directories to process
//

while (directoryStack.Count > 0)
{
string currentDir = directoryStack.Pop();
//
// Add all files at this directory.
//

foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))
{
fileResults.Add(fileName);
}

//
// Add all directories at this directory.
//

foreach (string directoryName in Directory.GetDirectories(currentDir))
{
directoryStack.Push(directoryName);
}
}
return fileResults.ToArray();
}
}

// To Test the Snippet which is mentioned above, the following code will help us

class Program
{
static void Main()
{
//
// Get all files in the allensamuel directory (calling convention).
//
string dir = @"C:\";
string[] fileNames = FileSystemUtil.GetAllFileNames(dir);

//
// Loop through all files in the string array.
//

foreach (string fileName in fileNames)
{
Console.WriteLine(fileName);
}
}
}

No comments:

Post a Comment