How to read a random line from a text file in c#?

How to read a random line from a text file in c#? If you want to read a random line from a text file in c#, you can using File.ReadLines Method (String).

File.ReadLines Method (String)

Reads the lines of a file.
public static IEnumerable ReadLines(
string path


Type: System.String

The file to read.

Return Value
Type: System.Collections.Generic.IEnumerable

All the lines of the file, or the lines that are the result of a query.

File.ReadLines Method (String) Examples

foreach (string line in File.ReadLines(@"d:\data\episodes.txt"))
if (line.Contains("episode") & line.Contains("2006"))

The ReadLines method in a LINQ query

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

class Program
static void Main(string[] args)
var files = from file in Directory.EnumerateFiles(@”c:\”, “*.txt”, SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains(“Microsoft”)
select new
File = file,
Line = line

foreach (var f in files)
Console.WriteLine(“{0}\t{1}”, f.File, f.Line);
Console.WriteLine(“{0} files found.”, files.Count().ToString());
catch (UnauthorizedAccessException UAEx)
catch (PathTooLongException PathEx)
Version Information
Universal Windows Platform: Available since 10
.NET Framework: Available since 4.0
Silverlight: Available since 4.0

Leave a Reply

Your email address will not be published.