'Why would console display different received string than message box in c#?

This is a follow up to my previous question. But it appears that for a reason I don't understand, the os is interpreting a received string differently than a message box is. This is apparent as when using message box.show function, it shows the correct string that was received. But the if then statement, the code for if the string equals what it does equal does not execute, and also the same string comes across as only system.byte it does not show in the console.

Here is the code:

SL_Click(object sender, EventArgs e)
{
    try
    {
        TcpClient tcpclnt = new TcpClient();
        tcpclnt.Connect(RecieveIP.Text, 8001); // receive the IP to listen from and port number for server.

        MessageBox.Show("Connected");

        Stream stm = tcpclnt.GetStream();

        MessageBox.Show("Listening for information......");

        byte[] bb = new byte[100];
        int k = stm.Read(bb, 0, 100);

        for (int i = 0; i < k; i++)
            Console.Write(Convert.ToString(bb));

        string atk = Encoding.ASCII.GetString(bb);
        MessageBox.Show("Received Command " + atk);

        if (atk == "g")
        {
            MessageBox.Show("working");
            Search.RunWorkerAsync();
        }
    }
}

I'm leaving out the actual background worker code is it works ok in other implementations.

I am wondering why this may be? Thanks.



Solution 1:[1]

i don't know why you don't have it in a "while" loop or something but never mind that... please try this:

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string data = Encoding.UTF8.GetString(bb.AsSpan(0, k ));
Console.WriteLine($"Data Received: {data}");//test

//if you want your check
//this will not work if your incoming data contains white space or other bytes that were converted.

if (data == "g" ||data.Contains("g"))//the .Contains can solve that prob, but a mix of letters containing "g" will trigger it
    {
        MessageBox.Show("working");
        Search.RunWorkerAsync();
    }

if your still having trouble please debug your incoming bytes and sent one.

make sure your not sending other bytes other the the "g" that you have send, if you use a different conversion method it might add additional bytes. Consider checking your sent and received bytes!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mario V