Code inspection: Actual number of bytes read by 'Stream.Read()' is ignored
This inspection identifies cases where the return value of Stream.Read
, representing the actual number of bytes read, is ignored. This can lead to incorrect processing of partially read data.
public void Test(Stream stream)
{
Span<byte> buffer = stackalloc byte[16];
stream.Read(buffer);
}
public void Test(Stream stream)
{
Span<byte> buffer = stackalloc byte[16];
stream.ReadExactly(buffer);
}
The suggested fix replaces Stream.Read
with Stream.ReadExactly
, ensuring that the entire buffer is read or an exception is thrown if that's not possible.
Last modified: 24 March 2025