The queue does not exist or you do not have suffic

2020-03-04 02:38发布

问题:

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.

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

Below is the mmc span in.

回答1:

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: