I've seen a few examples but none so far in C#, what is the best way to select a random file under a directory?
In this particular case I want to select a wallpaper from "C:\wallpapers" every 15 or so minutes.
Thanks.
I've seen a few examples but none so far in C#, what is the best way to select a random file under a directory?
In this particular case I want to select a wallpaper from "C:\wallpapers" every 15 or so minutes.
Thanks.
Get all files in an array and then retrieve one randomly
var rand = new Random();
var files = Directory.GetFiles("c:\\wallpapers","*.jpg");
return files[rand.Next(files.Length)];
If you're doing this for wallpapers, you don't want to just select a file at random because it won't appear random to the user.
What if you pick the same one three times in a row? Or alternate between two?
That's "random," but users don't like it.
See this post about how to display random pictures in a way users will like.
select random file from directory
private string getrandomfile2(string path)
{
string file = null;
if (!string.IsNullOrEmpty(path))
{
var extensions = new string[] { ".png", ".jpg", ".gif" };
try
{
var di = new DirectoryInfo(path);
var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower()));
Random R = new Random();
file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;
}
// probably should only catch specific exceptions
// throwable by the above methods.
catch {}
}
return file;
}
var files = new DirectoryInfo(@"C:\dev").GetFiles();
int index = new Random().Next(0, files.Length);
Console.WriteLine(files[index].Name);
why not just:
Use the Directory.GetFiles(...)
to get the array of filenames and use the Random
class to select a random file.