[英]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.