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

Recommended Answers

All 7 Replies

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?

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.

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

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

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.

@Ketsuekiame: ou are absolutely right! :)

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.