2012-03-08 39 views
0

我正在尝试获取MSMQ中的消息数。我发现在互联网上的代码(多次):无法获取MSMQ Com来查找我的队列

// 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); 

每次我去_queueManager.Init它失败,此错误:

The queue path name specified is invalid.

我已经检查(和双重检查)我的队列名称看看这是否是错误的。我尝试了不同的队列,不同的机器,运行远程,运行本地......没有任何工作。

我也尝试过上面的代码的变体。例如,我曾尝试:

_queueManager.Init("MyLaptopComputer", @"DIRECT=OS:MyLaptopComputer\PRIVATE$\MyQueue"); 

的队列与NServiceBus和功能就好用,当我用NServiceBus访问它们。

有没有人有关于如何让这个工作的想法?

+1

您是否尝试过使用“localhost”或“。”在你的道路上,而不是你明确的电脑名称? – 2012-03-08 17:50:08

+0

@SeanH我曾尝试“。”。但是,我应该在放弃之前尝试一下。看到我的答案,看看我的工作变化。 – Vaccano 2012-03-08 18:13:46

+0

为什么你在使用COM类时有一个完美的Api。网络框架,因为你使用的是C#? – 2012-03-08 22:53:05

回答

1

我认为问题是你得到的错误是有点误导。 MSMQManagement.Init需要3个参数。它们都是可选的,这就是为什么在其他语言(如VB)中,您有时会看到它只有2个参数。

有一个CodeProject project,显示了如何做你在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; 
} 

它可能会提供一个更好的起点。

0

原来,这是一个问题的组合。最大的缺点是我需要使用FormatName而不是路径名。

_queueManager.Init("MyComputer", null, @"DIRECT=OS:MyComputer\PRIVATE$\MyQueue"); 

而且,如果队列为空,它会抛出一个异常...

又爱COM接口。 :)