How can I load all files in a folder and sub folder?

I'm trying to make a C# music player and to do so, I'm using the WMP object found in win forms, I got it to load files from an specific folder on the press of a button, however, I want it to load every media file (FLAC, mp3, wav...) in an specific folder and its sub folders.

by now the code I have to load files is as follows.

string[] path, files; //Global Variables to get the path and the file name

       private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
       {
           //This function displays the files in the path and helps selecting an index
           axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex]; 
           axWindowsMediaPlayer1.uiMode = "None";
       }

       private void button1_Click(object sender, EventArgs e)
       {
           OpenFileDialog ofd = new OpenFileDialog();

           ofd.Multiselect = true;

           if(ofd.ShowDialog() == DialogResult.OK)
           {
               //Function that loads the files into the list.
               files = ofd.SafeFileNames;
               path = ofd.FileNames;

               for (int i = 0; i < files.Length; i++)
               {
                   listBox1.Items.Add(files[i]);
               }

           }
       }



Step 1: Use FolderBrowserDialog instead of OpenFileDialog, this helps you to select a folder instead of a file

Step 2: After selecting a file, You can use the method Directory.EnumerateFiles(Your_Path, ".", SearchOption.AllDirectories) to get all files in the selected folder.


Try this:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        axWindowsMediaPlayer1.URL = listBox1.Items[listBox1.SelectedIndex];
        axWindowsMediaPlayer1.uiMode = "None";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog FBD = new FolderBrowserDialog();

        if (FBD.ShowDialog() == DialogResult.OK)
        {
            LoadFiles(FBD.SelectedPath, new string[] { ".mp3", ".wav" }); //You can add more file extensions...
        }
    }

    private void LoadFiles(string FolderPath, string[] FileExtensions)
    {
        string[] Files = System.IO.Directory.GetFiles(FolderPath);
        string[] Directories = System.IO.Directory.GetDirectories(FolderPath);

        for (int i = 0; i < Directories.Length; i++)
        {
            LoadFiles(Directories[i], FileExtensions);
        }
        for (int i = 0; i < Files.Length; i++)
        {
            for (int j = 0; j < FileExtensions.Length; j++)
            {
                if (Files[i].ToLower().EndsWith(FileExtensions[j].ToLower()))
                {
                    listBox1.Items.Add(Files[i]);

                    break;
                }
            }
        }
    }