簡體   English   中英

如何加載文件夾和子文件夾中的所有文件?

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

我正在嘗試制作 C# 音樂播放器,為此,我使用的是在 win forms 中找到的 WMP object,我得到它來加載文件,但我希望它從特定文件夾加載文件加載特定文件夾及其子文件夾中的每個媒體文件(FLAC、mp3、wav...)。

現在我必須加載文件的代碼如下。

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]);
               }

           }
       }


第 1 步:使用FolderBrowserDialog而不是 OpenFileDialog,這可以幫助您 select 一個文件夾而不是一個文件

步驟 2:選擇文件后,您可以使用方法Directory.EnumerateFiles(Your_Path, " . ", SearchOption.AllDirectories)獲取所選文件夾中的所有文件。

嘗試這個:

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;
                }
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM