I have a function that converts a part of stream to a string:
private string GetString(Stream stream, int start, int length)
{
var buffer = new byte[length];
stream.Read(buffer, start, length);
return Encoding.UTF8.GetString(buffer, start, length);
}
I am working with pretty big stream and I don’t like to duplicate bytes (by converting part of stream to byte[]) just for being able to call Encoding.GetString. Is there any way to get string of some encoding from stream?
It’s not really clear what you’re trying to do – and the fact that you’re calling
Stream.Readwithout using the return value is alarming – but perhaps you’re looking forStreamReader? It’s aTextReaderwhich is backed by aStream, so you can read characters from it instead of binary data. This is appropriate if you’re reading from a stream which is entirely text data (at least from the current position when you pass is to the constructor; it could have binary data earlier).If you’re really trying to read data from just part of a stream, your code needs changing anyway –
Stream.Readdoesn’t do what you think it does in terms of the second parameter, which is the position within the buffer, not the position within the stream. You’d need to useStream.PositionorStream.Seek()to get to the right position in the stream.