ARTICLE

Access Row of a file Random bases using C#

Posted by Muhammad Shakir Articles | Visual C# January 01, 2007
In this aritical, we will look how to get a row of a file which contains multiple rows randomly.
Reader Level:

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.

Example

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.

Code 

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(); 

sr.Close();

Login to add your contents and source code to this article
post comment
     

Hi 


How are you? shall i know the reason of posting my picture, if you don't mind?

Regards,

Muhammad Shakir

Posted by Muhammad Shakir May 30, 2009
Posted by Kristipati Subramanyam May 30, 2009
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.