Edit

Share via


CA2022: Avoid inexact read with Stream.Read

Property Value
Rule ID CA2022
Title Avoid inexact read with Stream.Read
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As warning

Cause

A call to Stream.Read or Stream.ReadAsync is made and the return value isn't checked.

Rule description

Stream.Read and Stream.ReadAsync might return fewer bytes than requested, resulting in unreliable code if the return value isn't checked.

How to fix violations

To fix a violation, either check the return value (which is the total number of bytes read into the buffer) or call Stream.ReadExactly or Stream.ReadExactlyAsync instead.

Example

The following code snippet shows a violation of CA2022 and the fix for the violation.

void M1(Stream stream, byte[] buffer)
{
    // CA2022 violation.
    stream.Read(buffer, 0, buffer.Length);

    // Fix for the violation.
    stream.ReadExactly(buffer);
}
Shared Sub M(stream As Stream, buffer As Byte())
    ' CA2022 violation.
    stream.Read(buffer, 0, buffer.Length)

    ' Fix for the violation.
    stream.ReadExactly(buffer)
End Sub

When to suppress warnings

You shouldn't suppress warnings from this rule, as your app might hang if you don't fix the violations.

See also