C#, am I using StreamReader wrong?

Viewed 66

Alright. So the issue is, I'm trying to pick a random line on a certain file and assign it to a string variable. It's for whatever reason not letting me use StreamReader to read the line, how do I fix this and is there any reason as to why this is happening?

My code

The error I get

2 Answers

Let's solve the problem in general case. We don't know file length (number of lines) so we can't use Random.Next(length) comfortably (reading the entire file twice - once to obtain file length and then to get random line in not a good option) but we can use reservoire sampling:

private static T RandomElement<T>(IEnumerable<T> source, Random random) {
  if (source is null)
    throw new ArgumentNullException(nameof(source));

  if (random is null)
    random = new Random();

  T result = default(T);
  int count = 0;

  foreach (var item in source)
    if (random.Next(++count) == 0)
      result = item;

  return count > 0
    ? result
    : throw new ArgumentException("Empty sequence doesn't have random element", 
                                   nameof(source));
}

Then we can use our routine for our file:

Random random = new Random();  

...

string path = @"c:\MyFile.txt";

string randomLine = RandomElement(File.ReadLines(path), random);

ReadLine doesn't take a number as an argument, read the documentation. If you want to read a specific line, you'll have to read all the lines up to and including that line.

Related