In my C# application I receive MSMQ messages. Sometimes the message body is XML which I can handle without any problems. Sometimes the message could be of any data type so I just need to put it into a database table. To do this I need to take the message body and convert it in a “byte[]” type. My question is, how to convert the message body into byte[]?
            Asked
            
        
        
            Active
            
        
            Viewed 2,877 times
        
    2 Answers
2
            The Message object has a BodyStream property which exposes the body as a Stream, which you can then convert to a byte[] using the technique in this answer.
1
            
            
        Building off of answer by stuartd (so others visiting this page don't need to hunt)...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MSMQReader
{
    public class MSMQRead
    {
        public void DoIt()
        {
            var messageQueue = new System.Messaging.MessageQueue(@"FormatName:Direct=OS:<HOST NAME>\Private$\<PRIVATE QUEUE NAME>");
            var message = messageQueue.Receive(new TimeSpan(0, 0, 3)); // 3 SECOND TIMEOUT
            var messageBody = ConvertStreamToByteArray(message.BodyStream);
        }
        public byte[] ConvertStreamToByteArray(System.IO.Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                int chunk;
                while ((chunk = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, chunk);
                }
                return ms.ToArray();
            }
        }
    }
}
 
    
    
        barrypicker
        
- 9,740
- 11
- 65
- 79
 
     
    