Reputation: 82437
I am trying to get a count of messages in my MSMQ. I have found this code on the internet (many times):
// setup the queue management COM stuff
MSMQManagement _queueManager = new MSMQManagement();
object machine = "MyLaptopComputer";
object path = @"DIRECT=OS:MyLaptopComputer\PRIVATE$\MyQueue";
_queueManager.Init(ref machine, ref path);
Console.WriteLine(_queueManager.MessageCount);
Marshal.ReleaseComObject(_queueManager);
Every time I get to _queueManager.Init
it fails with this error:
The queue path name specified is invalid.
I have checked (and double checked) my queue name to see if that is wrong. I have tried different queues, different machines, running remote, running local... Nothing works.
I have also tried variations on the code above. For example I have tried:
_queueManager.Init("MyLaptopComputer", @"DIRECT=OS:MyLaptopComputer\PRIVATE$\MyQueue");
The queues are used with NServiceBus and function just fine when I use NServiceBus to access them.
Does anyone have an Idea on how I can get this to work?
Upvotes: 0
Views: 1670
Reputation: 82437
Turns out it was a combination of issues. The biggest being that I needed to use FormatName not path name.
_queueManager.Init("MyComputer", null, @"DIRECT=OS:MyComputer\PRIVATE$\MyQueue");
Also, it will throw an exception if the queue is empty...
Got to love COM interfaces. :)
Upvotes: 0
Reputation: 18965
I think the problem is the error you're getting is a little misguiding. MSMQManagement.Init
takes 3 parameters. They're all optional which is why in other languages (like VB) you'll sometimes see it called with only 2 parameters.
There is a CodeProject project that shows how to do what you're doing in C#:
private int GetMessageCount(string queueName)
{
int count = 0;
try
{
MSMQ.MSMQManagement mgmt = new MSMQ.MSMQManagement();
MSMQ.MSMQOutgoingQueueManagement outgoing;
String s = "YOURPCNAME";
Object ss = (Object)s;
String pathName = queueName;
Object pn = (Object)pathName;
String format = null;
Object f = (Object)format;
mgmt.Init(ref ss , ref f, ref pn);
outgoing = (MSMQ.MSMQOutgoingQueueManagement)mgmt;
count = outgoing.MessageCount;
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
return count;
}
It might provide a better starting point.
Upvotes: 1