I have a Service Broker Queue in the database that I'm trying to get the message body from. The result has has unnecessary whitespace, which I can't remove no matter what I try. I simply want to collapse everything and remove all extra whitespace. I've tried Regex, trimming, replace, etc.
Original Data in Queue:
0x31002C0020003200
Message Reciever:
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('\0');
}
catch (SqlException e)
{
Console.WriteLine(e);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex);
}
finally
{
reader.Close();
conn.Close();
}
}
return message;
}
Sample Output of 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
It looks like you're trying to read unicode/utf16 as utf8, which will end up with what can look like spaces, but is actually null characters.
You can use the unicode encoding instead, which should get you the desired result.
message = System.Text.Encoding.Unicode.GetString(binaryString);