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
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
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 ClassWhen to suppress warnings
You shouldn't suppress warnings from this rule, as your app might hang if you don't fix the violations.