Goodday people!

This time I am trying to index all files of a kind from any subdirectory. To index all files from a selected directory and 1 sublevel I use this code:

arrayCount = 0;
            DirectoryInfo di = new DirectoryInfo(SourceString);
            
            FileInfo[] rgFiles = di.GetFiles("*.mp3");
            foreach (FileInfo fi in rgFiles)
            {
                fileIndex[arrayCount] = fi.FullName;
                MessageBox.Show(fileIndex[arrayCount]); // Temp for testing
                arrayCount++;
            } 

            DirectoryInfo[] dirs = di.GetDirectories();
            
            foreach (DirectoryInfo diNext in dirs) 
            {   
                FileInfo[] rgFiles2 = diNext.GetFiles("*.mp3");
                foreach (FileInfo fi in rgFiles2)
                {
                    fileIndex[arrayCount] = fi.FullName;
                    MessageBox.Show(fileIndex[arrayCount]); // Temp for testing
                    arrayCount++;
                }
            }

Works great, next step is then to get it to read from any sublevel. I could copy/paste another "foreach" with directoryinfo inside this one but that still limits it from going to any subdirectory (and would be a pretty silly method to use).

Think you can point me in the right direction? :)

This is usually done with recursion:

void Fetch (string SourceString)
{
            arrayCount = 0;
            DirectoryInfo di = new DirectoryInfo(SourceString);
            
            FileInfo[] rgFiles = di.GetFiles("*.mp3");
            foreach (FileInfo fi in rgFiles)
            {
                fileIndex[arrayCount] = fi.FullName;
                MessageBox.Show(fileIndex[arrayCount]); // Temp for testing
                arrayCount++;
            } 

            DirectoryInfo[] dirs = di.GetDirectories();
            
            foreach (DirectoryInfo diNext in dirs) 
            {   
               Fetch(diNext.FullName); // HERE!
            }
}

Note: that code is non-buildable of course, i just put your code in a method to show you the way to go.

Ah! Works great, thanks allot :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.