C#idiomatic C#
ca2022fundamentals/code-analysis/quality-rules

Code analysis

CA2022: Avoid inexact read with Stream.Read

Learn about code analysis rule CA2022 - Avoid inexact read with Stream.Read

CA2022 Reliability enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule description

System.IO.Stream.Read and System.IO.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 System.IO.Stream.ReadExactly or System.IO.Stream.ReadExactlyAsync instead.

Example

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

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2022.cs1

csharp
using System.IO;

namespace ca2022;

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

        // Fix for the violation.
        stream.ReadExactly(buffer);
    }
    // </Snippet1>
}

sample · vbdocs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca2022.vb1

vb
Imports System.IO
Imports System.Threading

Public Class ca2022
    ' <Snippet1>
    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
    ' </Snippet1>

End Class

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