0

I have a StreamReader and I want to read the next n Bytes and return them as a string.

There is only a ReadLine() method returning a string, but my file has no linebreaks (CR/LF). Read() returns int instead and ReadBlock() fills a char[].

Is there a simple way to do it? Shall I use Encoding.GetString()? Then I would need to read into a byte[].

I see an issue with Encodings and characters with more than 1 Bytes, so to be exact, I want to read n bytes and the Encoding has to be taken into account.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
Timbu42
  • 107
  • 1
  • 1
  • 8
  • 1
    Does this answer your question? [How do I convert StreamReader to a string?](https://stackoverflow.com/questions/8606793/how-do-i-convert-streamreader-to-a-string) – Justin Lessard Apr 23 '20 at 15:55
  • As far as i see, it uses the ReadToEnd() method, so i dont think so, but thanks. – Timbu42 Apr 23 '20 at 16:44
  • Why do you have / are you using a `StreamReader`? It is intended for reading text files. You shouldn't use it for reading binary files. Also, "I want to read `n` bytes and the Encoding has to be taken into account" seems contradictory. Either you want to read `n` characters based on Encoding or you want to read `n` bytes ignoring Encoding. – NetMage Apr 23 '20 at 18:11
  • I am reading a text file! I just don't want to read linewise. I want to read n characters. Lets say each character is one byte. – Timbu42 Apr 24 '20 at 07:09

2 Answers2

1

this should help:

private byte[] ReadPartial(Stream source, byte[] buffer, int start, int length)
{
    //the second parameter on the streamreader 
    //says that it should detect the encoding
    using(var reader = new StreamReader(source, true))
    {
        reader.BaseStream.Read(buffer, start, length);
    }
    return buffer;
}
Isparia
  • 682
  • 5
  • 20
  • Thanks, but that's weird, if i read from my StreamReader by "reader.BaseStream.Read(buffer, 0, 4)" the array is left with zeros only, even though reader.ReadLine() at the same place gives me some text (e.g. "1X 72X23"). What am i doing wrong? Resulting int of the method is 0, so it didn't read anything i suppose? – Timbu42 Apr 23 '20 at 16:54
0

that's interesting:

This doesn't work (no reading, m=0):

        byte[] buffer = new byte[4];
        int m = sr.BaseStream.Read(buffer, 0, 4);
        string s = sr.CurrentEncoding.GetString(buffer);

but this does:

        char[] cs= new char[4];
        sr.ReadBlock(inhalt, 0, 4);
        string s = new string(cs);

Thus i assume using BaseStream just isn't a good idea.

Timbu42
  • 107
  • 1
  • 1
  • 8