Your text probably has more empty characters at the end (probably '\0'
), then when you print it looks like the value is only "007F", but actually it has several characters '\u0000'
, what makes the strings different. If you Trim
these characters of the end, you must get your correct comparison, as shown in the example below.
byte[] b = new byte[29];
var bi = 0;
b[bi++] = (byte)'2';
b[bi++] = (byte)'1';
b[bi++] = (byte)'1';
b[bi++] = (byte)'0';
b[bi++] = (byte)'0';
b[bi++] = (byte)'7';
b[bi++] = (byte)'F';
var tex = Encoding.ASCII.GetString(b);
Console.WriteLine("Retorno de Dados: " + tex);
Console.WriteLine("Retorno de Dados: <<" + tex + ">>"); // mostra os outros caracteres
Console.WriteLine(tex.Replace("211", "") == "007F"); // false, o primeiro string tem mais caracteres
Console.WriteLine(tex.Replace("211", "").Replace("\0", "") == "007F");
Another alternative is to use only the number of bytes that were received in the call to s.Receive
when to convert bytes to strings:
byte[] ret = new byte[29];
int bytesRecvd = s.Receive(ret);
Console.WriteLine("Retorno de Dados" +
(System.Text.Encoding.ASCII.GetString(ret, 0, bytesRecvd).Replace("211","")));
string tex = System.Text.Encoding.ASCII.GetString(ret, 0, bytesRecvd).Replace("211 ", "");
switch (tex)
{
case "007F": Console.WriteLine("Situação 1"); break;
}
Console.Readkey();
Thanks for the help! It worked perfectly.
– João K. Queiroz