Search code examples
c#bytefilestreamstreamreaderreadline

Reading files in c# with filestream and streamreader


I have a file, which contains data, I want to read it as byte[] and divide into 3 blocks. First line might be read as string, then 2nd block, might be 1-3 length of lines and all left bytes as block 3.

I was wondering, how can I get that block 1 and block 2 would be a string made of byte[], block 3 would be kept byte[].

File:

00256000 12      // block 1 single line
a2#b2#c2#d2#e2#  //
1#               //  block 2 readline doesn't fit, unknown length of lines
1#               //
—q3л             // block 3 left bytes

I was trying to do FileStream.Read(bytes, 0, file.length), but it only reads all bytes.

StreamReader.ReadLine() is suitable only for 1st line, but it reads plain string, not bytes, it skips '\n' , '\r' etc.

I don't know which way is better to read files and it would be perfect to read allbytes and somehow divide them to these 3 blocks, to have exact block size.


Solution

  • You can read all bytes and iterate through buffer searching for line endings. When you find line endings convert textparts with

    string text = Encoding.UTF8.GetString(buffer, start_len, end_len);
    

    p.s. be sure to use exact encoding... UTF8 is an example...