The queue does not exist or you do not have sufficient permissions to perform the operation. exception while sending message via MSMQ

Jitendra Pancholi picture Jitendra Pancholi · Mar 24, 2015 · Viewed 9.8k times · Source

I have created a function to send message via MSMQ but getting exception while executing. below is my function.

public void SendMessageToQueue(ChessQueue chessQueue)
{
    MessageQueue queue = null;
    Message m = null;
    if (!MessageQueue.Exists(".\\Private$\\" + chessQueue.QueueName))
    {
        queue = new MessageQueue(".\\Private$\\chessqueue");
        chessQueue.Messages = new List<MessageObject>();
        chessQueue.Messages.Add(chessQueue.Message);
        queue.Formatter = new BinaryMessageFormatter();
        m = new Message();
        m.Body = chessQueue;
    }
    else
    {
        queue = new MessageQueue(".\\Private$\\" + chessQueue.QueueName);
        queue.Formatter = new BinaryMessageFormatter();
        m = queue.Receive();
        ChessQueue ExistingChessQueue = m.Body as ChessQueue;
        ExistingChessQueue.Messages.Add(chessQueue.Message);
        m.Body = ExistingChessQueue;
    }            
    queue.Send(m);
    // Getting Exception at this Line
}

Exception:- The queue does not exist or you do not have sufficient permissions to perform the operation.

Also I'm unable to open security tab of Messaging Queue under Computer Management. See attached screenshot. enter image description here

I tried creating the message queue under private manually and system allowed me to do so. See below enter image description here

Below is the mmc span in. enter image description here

Answer

Hans Passant picture Hans Passant · Mar 26, 2015
if (!MessageQueue.Exists(".\\Private$\\" + chessQueue.QueueName))
{
    queue = new MessageQueue(".\\Private$\\chessqueue");
    // etc..

There are two bugs in this code. First problem is that it hard-codes the queue name in the string instead of using chessQueue.QueueName. A mismatch will be fatal of course. Second problem, and surely the most critical one, is that it doesn't actually create the queue. Proper code should resemble:

string name = ".\\Private$\\" + chessQueue.QueueName;
if (!MessageQueue.Exists(name))
{
    queue = MessageQueue.Create(name);
    // etc...

Looked like this after I ran this code, with one queue.Send() call:

enter image description here