I get a random line from file:
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));
}
}
But sometimes it turns out that the line is always null and loop is infinite. Please, where am I wrong?
This function is called 1000 times (for example). The first 100 calls are successful, but then the position of the main stream is the last position, and seek not worked.
ps: I want to get a random position in the file. Then read through the line on which this position to the end and return as result the following line. It is the fastest algorithm to obtain a random string of a large file in a loop. And yes, I know that this function never returns the first row.