Banner

Message of the Day

C#

// Michael Eaton
// Tue Jul 02 2002 18:34:59
// MessageOfTheDay
// Reads a random line from a text file that is in the form
// of 1 "message" per line and prints it to the screen.

using System;
using System.IO;

public class MessageOfTheDay {
    public static void Main(string[] args) {

        string theFile;
        // read from the arg list
        if (args.Length != 0) {
            theFile = args[0];
        } else {
            Console.WriteLine("usage: motd.exe <filename>");
            return;
        }

        if (File.Exists(theFile)) {
            Console.WriteLine(getMessage(theFile));
        } else {
            Console.WriteLine("The file: '{0}' does not exist.", theFile);
        }
    }

    private static string getMessage(string fileName) {
        int currentLine = 0;
        string text;
        StreamReader file = new StreamReader(fileName);
        Random generator = new Random();

        // this will give us a line between 0 and N where N is the number of lines
        // in the file.
        int randomNum = Convert.ToInt32((getNumberOfLines(fileName) * generator.NextDouble()) + 1);

        // we need to loop through the file and return the randomNum line
        while((text = file.ReadLine()) != null) {
            currentLine++;
            if (currentLine == randomNum) {
                file.Close();
                return text;
            }
        }
        file.Close();
        return "none";
    }

    private static int getNumberOfLines(string filename) {
        // counts the number of lines in a file
        StreamReader file = new StreamReader(filename);
        int lines = 0;
        while(file.ReadLine() != null) {

            lines++;
        }
        file.Close();
        return lines;
    }
}
csharpindex.com/colorCode
Save as 'motd.cs'.
Compile at the command-line using: 'csc hello.cs'
Back to the samples...