Here is just a little tutorial to list all the files in a folder (and its subfolders).
Output:
C# Code and Comment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | //using System.Collections.Specialized; //using System.IO; class Program { // List all the files in a folder (and its subfolders): // 'allFiles' is my StringCollection containing the complete list of all files // Why a StringCollection? Because arrays have a fixed size and using a StringCollection is the only way to list all the folder and subfolder files. // 'path' the selected folder // // 'ext' the list of extensions to filter the files listed // // 'scanDirOk' a boolean allowing me to accept subfolder scans // public static StringCollection listAllFiles(StringCollection allFiles, string path, string ext, bool scanDirOk) { // listFilesCurrDir: Table containing the list of files in the 'path' folder string[] listFilesCurrDir = Directory.GetFiles(path, ext); // read the array 'listFilesCurrDir' foreach (string rowFile in listFilesCurrDir) { // If the file is not already in the 'allFiles' list if (allFiles.Contains(rowFile) == false) { // Add the file (at least its address) to 'allFiles' allFiles.Add(rowFile); } } // Clear the 'listFilesCurrDir' table for the next list of subfolders listFilesCurrDir = null; // If you allow subfolders to be read if (scanDirOk) { // List all the subfolders present in the 'path' string[] listDirCurrDir = Directory.GetDirectories(path); // if there are subfolders (if the list is not empty) if (listDirCurrDir.Length != 0) { // read the array 'listDirCurrDir' foreach (string rowDir in listDirCurrDir) { // Restart the procedure to scan each subfolder listAllFiles(allFiles, rowDir, ext, scanDirOk); } } // Clear the 'listDirCurrDir' table for the next list of subfolders listDirCurrDir = null; } // return 'allFiles' return allFiles; } static void Main(string[] args) { //reading sample StringCollection allFiles=new StringCollection(); listAllFiles(allFiles, @"D:\sample", "*.txt", true); foreach (Object obj in allFiles) Console.WriteLine(" {0}", obj); Console.WriteLine(); Console.ReadLine(); } } |