How to randonly read a single line from a text file using C#?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 406
The below program will do so

using System;
using System.IO;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fileName = @"D:\Input.txt";

Console.WriteLine(File.ReadLines(fileName).ToList()[GetRandomNumbers(1, 20)]);
Console.ReadKey();
}

//generate random numbers
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
private static int GetRandomNumbers(int minVal, int maxVal)
{
lock (syncLock) return random.Next(minVal, maxVal);
}
}
}

Comments or Responses

Login to post response