简体   繁体   English

C#,我使用 StreamReader 错了吗?

[英]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?出于某种原因不让我使用 StreamReader 来阅读该行,我该如何解决这个问题,是否有任何理由说明为什么会发生这种情况?

My code我的代码

The error I get我得到的错误

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 :我们不知道文件长度(行数),所以我们不能舒适地使用Random.Next(length) (读取整个文件两次- 一次获取文件长度,然后获取随机行不是一个好的选择)但是我们可以使用水库采样

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 . ReadLine不接受数字作为参数, 请阅读文档 If you want to read a specific line, you'll have to read all the lines up to and including that line.如果您想阅读特定的行,则必须阅读直到并包括该行的所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM