且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C#中的目录中获取文件列表

更新时间:2023-11-12 22:26:22

您已经通过以下方式获得了您想要的所有文件:

You already get all the files you want by:

string[] music = Directory.GetFiles(dir, "*.mp3");

GetFiles 返回文件夹中的所有文件,如果您的搜索模式为 *mp3,它将返回所有 MP3 文件.

GetFiles return all files in the folder and with your search pattern as *mp3, it returns all MP3 files already.

问题是,你不需要为文件做string.Join,而是一个一个地播放它们:

The thing is, you do not need to do string.Join for the files, but play them one by one:

foreach (var musicurl in music){
    WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    wplayer.URL = musicurl; //get one by one
    wplayer.controls.play();
    //Logic to control how long a music is to be played
}

您当前的逻辑仅在您的文件夹中只有一个 MP3 文件时才有效的原因是因为您使用了 string.Join.

The reason why your current logic only works when you have exactly one MP3 file in your folder is because of the string.Join that you use.

举例来说,当您有多个文件时,这就是 string.Joinmusic 中的作用.假设您的 music 包括:

To illustrate, this is what the string.Join do for in your music when you have more than one files. Suppose your music consists of:

C:\music1.mp3
C:\music2.mp3

当你执行 string.Join 时,你的 URL 变成:

When you do string.Join, your URL becomes:

C:\music1.mp3 C:\music2.mp3

因此您无法播放音乐.但是当你只有一个文件的时候,字符串join没有影响:

Thus you cannot play the music. But when you only have one file, the string join does not affect:

C:\music1.mp3