Connecting Tech Pros Worldwide Forums | Help | Site Map

Problem Reading a Text File Backwards C#

Member
 
Join Date: Sep 2007
Posts: 70
#1: Jun 5 '08
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,split). 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...

Expand|Select|Wrap|Line Numbers
  1.  using (FileStream fs = new FileStream(sFullPathAndFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  2. {
  3.    fs.Seek(iBBFileSize+iBytesPerRead, SeekOrigin.Begin);
  4.    byte[] BBLog = new byte[posBytesPerRead];
  5.    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  6.    //lTotalBytes is a negative number used to offset to the position to start read
  7.    //iBytesPerRead is a negative number
  8.    //posBytesPerRead is the positive version of iBytesPerRead
  9.    //iBR represents bytes read
  10.    while (found == 0 && fs.Position>posBytesPerRead)
  11.    {
  12.      iBR = fs.Read(BBLog, 0, posBytesPerRead);
  13.      lTotalBytes -= iBR;
  14.      BBString = enc.GetString(BBLog);
  15.      BBLines = BBString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  16.      iBBLineCount = BBLines.Length;
  17.      //Removed string array iteration/parsing
  18.      iFirstlinelength = BBLines[0].Length;
  19.      lTotalBytes += iFirstlinelength;
  20.      fs.Seek(iBBFileSize + lTotalBytes + (2*iBBLineCount), SeekOrigin.Begin);
  21.    }

Member
 
Join Date: Sep 2007
Posts: 70
#2: Jun 9 '08

re: Problem Reading a Text File Backwards C#


I've taken the out the (2*iBBLineCount) from the last line (which was the was I originally programmed this), but it still does not seem to work. Very strange, because this looks right to me. One observation is that when I look at my watch window at breakpoints, I see some really strange results, like my string array (BBLines) not being updated every read.
Reply