从目录树中获取随机文件

Kev*_*lia 0 c# linq directory-tree

所以我似乎无法在任何地方找到一个很好的例子。我从这个从目录中选择随机文件的问题中找到了一个很好的例子,但我需要从目录树(未知深度)中选择一个随机文件。这段代码从 1 个目录中获取一个随机文件,但我对如何将它扩展到所有子目录感到困惑,我相信你们中的一个 LINQ 专家可以帮助我制作一些东西。

var extensions = new string[] { ".mp3" };
var di = new DirectoryInfo(MusicPath);
var rgFiles = di.GetFiles("*.*")
    .Where( f => extensions.Contains( f.Extension.ToLower() ));
int fileCount = rgFiles.Count();
if (fileCount > 0)
{
    int x = this.Generator.Next( 0, fileCount );  //Generator is 'Random' object
    file = rgFiles.ElementAt(x).FullName;
}
Run Code Online (Sandbox Code Playgroud)

Kan*_*ane 5

尝试这个

var random = new Random(); // this should be placed in a static member variable, but is ok for this example
var fileNames = System.IO.Directory.GetFiles(@"c:\temp", "*.mp3", SearchOption.AllDirectories);
var randomFile = fileNames[random.Next(0, fileNames.Length)];
Run Code Online (Sandbox Code Playgroud)