Question

So I can't seem to find a good example of this anywhere. I found a good example from this question of picking a random file from a directory, but I need to pick a random file from a directory tree (of unknown depth). This code gets a random file from 1 directory, but I have been perplexed as to how to extend it to all sub directories as well, I'm sure one of you LINQ gurus out there can help me craft something.

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;
}
Was it helpful?

Solution

Try this

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)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top