1,105,644 Community Members

Read and display random string from file

Member Avatar
justin3085
Newbie Poster
4 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have an app put together that reads from a text file using streamreader. I have it coded, maybe not the best but it returns only the first line in the text file. I'm trying to get it to select a random line each time a button is pressed.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Drug_Test_Selection
{
       
    public partial class Form1 : Form
    {
        private List<string> ssn = new List<string>();
        private Random rand = new Random();

                
        public Form1()
        {
            InitializeComponent();
        
        }

        
        private void label1_Click(object sender, EventArgs e)
        {
            
        }

        private void caseTxt_TextChanged(object sender, EventArgs e)
        {
            //holds case number informaion
        }

        private void resetBtn_Click(object sender, EventArgs e)
        {
            casePrintTxt.Clear();
            oicPrintTxt.Clear();
            resultsTxt.Clear();
            dateTime.Clear();
            caseTxt.Clear();
            oicTxt.Clear();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void oicTxt_TextChanged(object sender, EventArgs e)
        {
            //Holds OIC information
        }

        private void resultsTxt_TextChanged(object sender, EventArgs e)
        {
            //returns the random social security number 
        }

        private void processBtn_Click(object sender, EventArgs e)
        {

            using (StreamReader sr = new StreamReader(@"C:\dev\social.txt"))
            resultsTxt.AppendText(sr.ReadLine());
                        
            
            casePrintTxt.Text = caseTxt.Text;
            oicPrintTxt.Text = oicTxt.Text;
            dateTime.Text = DateTime.Now.ToString();
            
            
            
          
            }
        }
    }
Member Avatar
james6754
Posting Whiz in Training
226 posts since Dec 2010
Reputation Points: 39 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]
 
0
 

return a random number..?? in what context do you mean???

to get a random number..use the next method of the random class....

Random myRand = new Random();

MessageBox.Show(myRand.Next(1,100)); //this will return a number between 1 and 100.

is this what you want?
Member Avatar
justin3085
Newbie Poster
4 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

return a random number..?? in what context do you mean???

to get a random number..use the next method of the random class....

Random myRand = new Random();

MessageBox.Show(myRand.Next(1,100)); //this will return a number between 1 and 100.

is this what you want?

My fault, random line from the text file not a random number. sorry :)
The text file is already populated with what I want in there also.

Member Avatar
james6754
Posting Whiz in Training
226 posts since Dec 2010
Reputation Points: 39 [?]
Q&As Helped to Solve: 22 [?]
Skill Endorsements: 4 [?]
 
0
 

Well something like this will read a random line...there isnt actually a method to do this...

int totalnumoflines = File.ReadAllLines(@"C:\whatever\whatever\whatever\whatever.txt").Length;
            Random random = new Random();
            int myrandline = random.Next(0, totalnumoflines);
            
            using (StreamReader readme = new StreamReader(@"C:\whatever\whatever\whatever\whatever.txt"))
            {
              
                string randline = null;
                for (int i = 0; i < myrandline; ++i)
                {      
                    randline = readme.ReadLine();
                }
               
                Console.WriteLine("The random line of text is, {0}", randline);
            }
Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
1
 

First put the lines of your file in a List like this:

// Read in all lines in the file, and then convert to List with LINQ.
        List<string> fileLines = File.ReadAllLines("file.txt").ToList();

then select a random line by indexing the list. See here: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

Member Avatar
Ketsuekiame
Posting Virtuoso
1,676 posts since May 2010
Reputation Points: 793 [?]
Q&As Helped to Solve: 231 [?]
Skill Endorsements: 27 [?]
 
1
 

First put the lines of your file in a List like this:

// Read in all lines in the file, and then convert to List with LINQ.
        List<string> fileLines = File.ReadAllLines("file.txt").ToList();

then select a random line by indexing the list. See here: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

This is the thirst method I also thought of, however, this can eat your memory and eventually crash if you have a very large file and not much memory. It would also consistantly, take a very long time (with large files)

A quick google found me this:

public string RandomLine( StreamReader reader )
{
    string chosen = null;
    int numberSeen = 0;
    var rng = new Random();
    while ((string line = reader.ReadLine()) != null)
    {
        if (rng.NextInt(++numberSeen) == 0)
        {
            chosen = line;
        }
    }
    return chosen;
}

This has the advantage of, if the random line is found at the beginning of the file, you haven't just read in a huge amount of data for nothing, speeding up the execution time. But this will also take a very long time if it manages to read all the way to the end.
Also, this will not eat away at the available memory.

In short: If your file is going to be relatively small ( < 500Mb ) I would use ddanbe's method, otherwise, something like the above would be better, simply to avoid eating memory.

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

@Ketsuekiame: ou are absolutely right! :)

Member Avatar
justin3085
Newbie Poster
4 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Excellent. All i need thank you for the replies. Greatly appreciated.

Question Answered as of 3 Years Ago by ddanbe, james6754 and Ketsuekiame
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article