Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(CA2022) How am I supposed to read correctly from a NetworkStream without knowing the incoming data size? #7521

Open
grallbring opened this issue Dec 28, 2024 · 1 comment

Comments

@grallbring
Copy link

grallbring commented Dec 28, 2024

Using this code snippet, I'm connecting to a TCP server, write a short message to it and then read it's response.

using (TcpClient tcpClient = new TcpClient())
{
    tcpClient.Connect("localhost", 8888);

    using (NetworkStream networkStream = tcpClient.GetStream())
    {
        networkStream.Write([0x01, 0x01]);

        byte[] data = new byte[1_024];

        networkStream.Read(data, 0, data.Length);
    }
}

Since I don't know the length of the response the server sends to me I create a buffer that I'm sure is large enough for it (1024 bytes).
Using networkStream.Read(data, 0, data.Length); to then read into that stream gives me a CA2022 warning: Avoid inexact read with 'System.Net.Sockets.NetworkStream.Read(byte[], int, int)', suggesting I should use NetworkStream.ReadExactly instead.
This will block execution forever since the server never sends data that's 1024 bytes long to me.

My question is what the correct way is to do this without receiving this warning.
Thanks!

@mpidash
Copy link
Contributor

mpidash commented Jan 6, 2025

You can check the return value of networkStream.Read(data, 0, data.Length) to see how much data you received. This is also suggested in the doc of CA2022 on how to fix a violation:

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

The fixer of CA2022 assumed that you always wanted to read exactly 1024 bytes (since you did not check the return value).
Here is another document that outlines recommended actions when working with Stream.Read and Stream.ReadAsync.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants