首页 文章

读取文件时无限循环

提问于
浏览
0

我从文件中得到一个随机行:

using (FileStream ifs = new FileStream(path, FileMode.Open, FileAccess.Read)) {
    using (StreamReader sr = new StreamReader(ifs, Encoding)) {
        long lastPos = ifs.Seek(0, SeekOrigin.End);
        long rndPos = 0;
          do {
              rndPos = (long)(Random.NextDouble() * lastPos);// Random is property
              ifs.Seek(rndPos, SeekOrigin.Begin);
              sr.ReadLine();
              line = sr.ReadLine();
          } while (string.IsNullOrWhiteSpace(line));
    }
}

但有时事实证明,该行始终为null并且循环是无限的 . 拜托,我哪里错了?

该函数被调用1000次(例如) . 前100个调用成功,但是主流的位置是最后一个位置,并且寻求不起作用 .

ps:我想在文件中获得一个随机位置 . 然后读取此位置到最后的行,并返回以下行 . 它是在循环中获取大文件的随机字符串的最快算法 . 是的,我知道这个函数永远不会返回第一行 .

2 回答

  • 0
    public string ReturnRandomLine(string path, ref Random r)
    {
        string[] lines = File.ReadAllLines(path);
        string randomLine = String.Empty;
        int randomLineNumber;
    
        do
        {
            randomLineNumber = r.Next(0, lines.Length - 1);
            randomLine = lines[randomLineNumber];
        } while (String.IsNullOrWhiteSpace(randomLine));
    
        return @"Line #" + randomLineNumber + " " + randomLine;
    }
    
  • 0

    好吧,如果该行为null,并且您的条件为string.IsNullOrWhiteSpace(line),那么它将是一个无限循环 .

相关问题