select random file from directory
21,977
Solution 1
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;
}
Solution 2
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)];
Solution 3
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.
Solution 4
var files = new DirectoryInfo(@"C:\dev").GetFiles();
int index = new Random().Next(0, files.Length);
Console.WriteLine(files[index].Name);
Solution 5
why not just:
- get the files into an array
- use the Random class to select a number that is random between 0 and files.Length
- Grab the file from the array using the random number as the index
Comments
-
Crash893 about 4 years
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.
-
Rich about 15 yearsWhen shuffling you should probably also account for the case that a file gets deleted or added to the directory (in which case you need to re-shuffle).
-
discoverAnkit over 9 yearsI tried this code snippet and its working fine but it is only searching in the folder wallpapers and not searching any sub-folders inside wallpapers. How to modify the code to do that as well?
-
Mouk over 9 yearsConsider passing SearchOption.AllDirectories as a third argument to the GetFiles method.
-
Guffa almost 9 yearsCatching exceptions and silently ignoring them is bad. You should either handle the exception and return something useful, or not catch them at all.