How to randomly choose a string from a string[] [C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
I have a folder [Souds\Backgrounds] full on Midi files which I can play using a function [PlayMidiFile(string MidiFile)] and everything works fine...
Thing is this folder [Souds\Backgrounds] has a large amount of Midi files (and some other non-music files that must be ignored) and I want my program to randomly choose one everytime it starts...
So, essentially I want to pass into [PlayMidiFiles] a string (MidiFile) representing the filename (with path) of a randomly selected Midi file in the [Souds\Backgrounds] folder...

So far this is what I have, I am able to get a string[] with a list of all the possible midi files, but now how do I RANDOMLY select one?
Code:
string sSelected = null;
string[] sFileList = System.IO.Directory.GetFiles("Sounds\\Backgrounds", "*.mid");

// ... Randomly select one of the strings from sFileList[] and put it in sSelected ...

// Play Selected File
if (PlayMidiFile(sSelected) == 0)
	return true;
else
	return false;
So, I need to somehow fill the string variable "sSelected" with one of the random values in "sFileList"

Any ideas, hints, and help would be greatly appreciated, thanks
 
the simplest way to get a random item from an array is using the Random class, so like in your case, it would be something like this:

Code:
string[] items = ...loaded items...;
Random r = new Random();
int randomedIndex = r.Next(0, items.Length - 1);

then u can just do whatever by getting the item that corresponds to that random number that was constrained to the array's length:
Code:
string selected = "";
selected = items[randomedIndex];

Some people will tell you that .Net's Random class is very far from being random, but it is simple to implement. If you want a more random number generator then look around on google, there are quite a bit out there.
 
If it is true that the .Net Random class is not very "random," it hardly matters in the context of picking a random song. The only time this might ever be an issue is in some sort of scientific or mathematical application.
 
If you want to make sure each item is played once before duplicates then you could load the filenames into an array and then randomise the array, then just keep selecting the next item in the array.

C#:
string[] items = ...loaded items...;
Random r = new Random();
byte[] b = new byte[items.Length];
r.NextBytes(b);
Array.Sort(b, items);
 
Back
Top