I have written a Windows App in C# that needs to read a text file over the network, starting from the end of the file and reading backwards toward the beginning (looking for the last occurrence of a couple of strings in one line of text). I do not want to read the entire file, as it is very large, on a highly utilized server, and is updated with hundreds of lines of text every second. So since I am reading backwards, I do a seek, then read, then encode the byte array as a string, split the string into an array of lines, then iterate and search through the string array. My problem is that since the first or 0 element of my string array will almost always be an incomplete line, to ensure 100% reliability I need to adjust the next seek so that I read the entire line that was incomplete/truncated on the last read (it would ideally be the final element of the next string array after the read,encode,spl it). So everything works great except that I can't seem to adjust the Seek to always read the whole truncated line. Most of the time it works, but not 100%, and therefore is useless :). I must be doing something wrong with the counting of the bytes or "\r\n"s. Any reasonable help would be appreciated. Code is below...
Code:
using (FileStream fs = new FileStream(sFullPathAndFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fs.Seek(iBBFileSize+iBytesPerRead, SeekOrigin.Begin);
byte[] BBLog = new byte[posBytesPerRead];
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
//lTotalBytes is a negative number used to offset to the position to start read
//iBytesPerRead is a negative number
//posBytesPerRead is the positive version of iBytesPerRead
//iBR represents bytes read
while (found == 0 && fs.Position>posBytesPerRead)
{
iBR = fs.Read(BBLog, 0, posBytesPerRead);
lTotalBytes -= iBR;
BBString = enc.GetString(BBLog);
BBLines = BBString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
iBBLineCount = BBLines.Length;
//Removed string array iteration/parsing
iFirstlinelength = BBLines[0].Length;
lTotalBytes += iFirstlinelength;
fs.Seek(iBBFileSize + lTotalBytes + (2*iBBLineCount), SeekOrigin.Begin);
}
Comment