字节数组有无法删除的空格

byte array has whitespace that can't be removed

我在数据库中有一个 Service Broker 队列,我正试图从中获取消息正文。结果有不必要的空格,无论我尝试什么都无法删除。我只是想折叠所有内容并删除所有多余的空格。我试过正则表达式、修剪、替换等。

队列中的原始数据:

0x31002C0020003200

消息接收者:

public string RecieveMessage()
    {
        string message = string.Empty;
        byte[] binaryString = new byte[100];            

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();

            var sql = "RECEIVE TOP(1) message_body FROM [dbo].[Queue]";
            var cmd = new SqlCommand(sql, conn);

            SqlDataReader reader = cmd.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    binaryString = (byte[])reader[0];
                }

                message = System.Text.Encoding.UTF8.GetString(binaryString).Trim('[=10=]');
            }
            catch (SqlException e)
            {
                Console.WriteLine(e);
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                reader.Close();
                conn.Close();
            }
        }

        return message;
    }

Console.WriteLine(message);

的示例输出

2 3 5 6 5 3, J o h n D o e & A s s o c i a t e s

您似乎在尝试将 unicode/utf16 读取为 utf8,这将以看起来像空格但实际上是空字符的形式结束。

您可以改用 unicode 编码,这应该会得到您想要的结果。

message = System.Text.Encoding.Unicode.GetString(binaryString);
  byte[] data = new byte[1024];
   clientSocket.Receive(data);
       
 string returndata = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
 returndata = returndata.Trim('[=10=]');