Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#, am I using StreamReader wrong?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The error I get

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading