Access Row of a file Random bases using C#

Select a Row Randomly

In the beginning,it is very difficult for new programmer to get a selected row between multiple rows of IO files, specially if you have a different passwords IO file and want to access a password randomly.

In C# language, it is very simple. There is a build-in function in C# language that is " Random ". You creat a random object and mension size of rows from which you want to select a row. Next function  of Random is used which select a row randomly. it returns int.


Here is example, which everyone likes to look practically demonstration. In this example, i am declearing an object of StreamReader which is taking a path string as parameter and giving my sample file path which contain my different passwords. Also deleared an array which is containing different passwords rows of my password file using a loop.

Decleared an object of Random function and pass no of rows of my passwords file to Next function of Random object (i.e rm.Next(10)), which is returning an int digit that is my selected password line number. Then giving num to array as index and getting that line password and passing to my string object. Now you may use password string in any kind of usage.


StreamReader sr = new StreamReader("d:\\passwords.txt");

String pwd = null;

string[] line = new string[10];

for (int i = 0; i < 10; i++)


     line[i] = sr.ReadLine();


Random rn = new Random();

int rnum = rn.Next(10);

pwd = line[rnum].ToString(); 


Similar Articles