c# FileStream Read having problems with StreamReader EndOfStream -


as title says found problem. little story first: have file.txt looking this:

aaaabb ccccddd eeeefffffff 

there many ways read text line-by-line, 1 of this:

streamreader sr = new streamreader("file.txt"); while(!sr.endofstream) {     string s = sr.readline(); } sr.close(); 

works. s gets each line. need first 4 letters bytes , rest string. after looking things , experimenting little, found easiest way this:

filestream fs = new filestream("file.txt", filemode.open); streamreader sr = new streamreader(fs); byte[] arr = new byte[4]; fs.read(arr, 0, 4); string s = sr.readline(); sr.close(); fs.close(); 

works. arr contains first 4 letters bytes , rest of line saved in s. single line. if add while:

filestream fs = new filestream("file.txt", filemode.open); streamreader sr = new streamreader(fs); while(!sr.endofstream) {     byte[] arr = new byte[4];     fs.read(arr, 0, 4);     string s = sr.readline(); }  sr.close(); fs.close(); 

now there's problem. arr doesn't , s reads whole line including first 4 letters. more strange if use while(true) (and assume else not example) works intended, 4 characters bytes , rest string, , same every line.

question missing? why happening? how solve this? or possible bug?

the problem here simple buffering. when attach streamreader filestream, automatically consumes block file, advancing current position of filestream. example file , default buffer size, once streamreader attaches itself, consumes entire file buffer, leaving filestream @ eof. when attempt read 4 bytes filestream directly via fs reference, there's nothing left consume. following readline works on sr reference that's reading buffered file content.

here's happens described steps:

  1. fs opens file , sits @ position 0.
  2. sr wraps fs , consumes (in case) 27 bytes internal buffer. @ point, fs position sits @ eof.
  3. you attempt read fs directly, @ eof no more bytes.
  4. sr.readline reads buffer built in step #2 , works well.

to fix specific error case, change byte array char array , use sr.read instead. i.e.

char[] arr = new char[4]; sr.read(arr, 0, 4); 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -