Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select random file from directory

Tags:

c#

.net

file

random

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.

like image 951
Crash893 Avatar asked Apr 13 '09 00:04

Crash893


People also ask

How do I randomly select files from a folder?

Right-click the folder in the left-hand pane — not the right — and click the new “Select Random” option. RandomSelectionTool then selects something from the contents of that folder — either a file, or a folder — and the right-hand pane should be updated to display it.

How do I select random files in file Explorer?

Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.

How do I select random files using my keyboard?

Windows method one Click on one of the files or folders you want to select. Hold down the control key (Ctrl). Click on the other files or folders that you want to select while holding the control key. Continue to hold down the control key until you select all the files you want.


2 Answers

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)];
like image 170
Mouk Avatar answered Sep 28 '22 16:09

Mouk


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.

like image 36
Jason Cohen Avatar answered Sep 28 '22 18:09

Jason Cohen