This article describes how to send and receiving messages in MSMQ using C#.
Introduction
MSMQ stands for Microsoft Message Queuing is one of the most reliable way to sending and receiving messages from one system to another system; both system can be located at different geographical locations. The benefit of MSMQ is that the receiving application doesn't have to run at the time of sending the message. Messages are stored in the queue of the system (Microsoft Operating System) and once the receiving application runs, it starts peeking the messages one by one.

Picture - 1
I have written hundreds of .NET How to's solution (ebook + source code + video) series based on real time project problems, click here to get it.
Namespace to use
To work with MSMQ, you will need to use following namespace.
using System.Messaging;
Creating a Queue in the system
Creating a queue in the system is an easy task. Go to My Computer and right click, select Manage and explore the nodes as displayed in the picture below.

Picture - 2
Right click the Private Queues and select New > Priovate Queue and create a queue. Alternatively, this can be done using C# code as well. My code snippet below does that automatically (ie. if queue doesn't exists, it creates otherwise use the existing one).
Writing the Queue name
The queue name should be written in specific format in order to access them programatically.
const string queueName = @".\private$\TestQueue";
In the above code, you can see that the name starts with "." and then private followed by $ symbol and then the actual queue name is written.
Now, let's send a message to the MSMQ using C#
Below code receive a queue name and sends an object to the queue as message. In this case I am using Person class that has two properties, FirstName and LastName as displayed below.
// create a class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now, lets see the actual SendMessageToQueue method. Below method, first checks for the existence of the queue, if it doesn't exists then create one else use it. Next, under the try block, it creates the instance of the Person object and sets its values. Using Send method of the MessageQueue object, it sends the message to the queue. Next couple of lines are catch block that execute in case any error occur.
private static void SendMessageToQueue(string queueName)
{
// check if queue exists, if not create it
MessageQueue msMq = null;
if (!MessageQueue.Exists(queueName))
{
msMq = MessageQueue.Create(queueName);
}
else
{
msMq = new MessageQueue(queueName);
}
try
{
// msMq.Send("Sending data to MSMQ at " + DateTime.Now.ToString());
Person p = new Person()
{
FirstName = "ITFunda",
LastName=".Com"
};
msMq.Send(p);
}
catch (MessageQueueException ee)
{
Console.Write(ee.ToString());
}
catch (Exception eee)
{
Console.Write(eee.ToString());
}
finally
{
msMq.Close();
}
Console.WriteLine("Message sent ......");
}
Look at the above picture - 2, you will see that there is a message displayed at the right side panel.
Receiving messages from MSMQ using C#
To receive a message from queue, we need to first instantiate the queue using MessageQueue. You will need to make sure that the queue exists, otherwise you shall get an error. Under the try block I have used XmlMessageFormatter object to specify the format of the message I have in the queue. The next line unboxed the body of the message to the Person object and writes its property on the console (you can see the first image above). Following lines are catch blocks that execute if any error occur.
private static void ReceiveMessageFromQueue(string queueName)
{
MessageQueue msMq = msMq = new MessageQueue(queueName);
try
{
// msMq.Formatter = new XmlMessageFormatter(new Type[] {typeof(string)});
msMq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Person) });
var message = (Person)msMq.Receive().Body;
Console.WriteLine("FirstName: " + message.FirstName + ", LastName: " + message.LastName);
// Console.WriteLine(message.Body.ToString());
}
catch (MessageQueueException ee)
{
Console.Write(ee.ToString());
}
catch (Exception eee)
{
Console.Write(eee.ToString());
}
finally
{
msMq.Close();
}
Console.WriteLine("Message received ......");
}
Sending and Receiving string/plain text to the MSMQ
Sending and receiving string to the MSMQ has been also covered in the above code snippet, you need to uncomment the corresponding lines of code from above two methods and comment the lines that is sending and receiving the Person object.
The complete source code for console application that creates, sends and receives data in MSMQ is attached with this article. Feel free to download and use it.
Reference
- http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.aspx
Conclusion
By writing few lines of code, we can communicate with the Microsoft Messaging Queue. MSMQ supports transactional communication as well so that in case you are sending multiple message related with one another and one message fails, all should rollback. Apart from this, you have ability to send and receive asynchronous messages as well.