我尝试访问Windows消息队列的消息:
var activeQueue = new MessageQueue("\\myhost\\private$\\just.a.queue", QueueAccessMode.Receive);
foreach(message in _activeQueue.GetAllMessages().ToList()) {
Console.WriteLine(message.Body);
}
我在尝试访问message.Body
时收到InvalidOperationException(并且几乎除Id之外的所有其他属性 - 字段)。
答案 0 :(得分:5)
感谢@SonerGönül我能够解决我的问题。这是解决方案:
message.Formatter = new ActiveXMessageFormatter();
var reader = new StreamReader(message.BodyStream);
var msgBody = reader.ReadToEnd();
Console.WriteLine(msgBody)
答案 1 :(得分:1)
另外,如何使用格式化程序解码消息有两种可能性:
Queue.Formatter = new MessageFormatter(); // Set formatter on queue
Msg = Queue.Receive();
Body = Msg.Body;
或
Msg = Queue.Receive();
Msg.Formatter = new MessageFormatter(); // Set formatter on msg
Body = Msg.Body;
也可以合并:
Queue.Formatter = new MessageFormatter();
Msg = Queue.Receive();
if(Msg.Label.Contains('Other')) Msg.Formatter = new OtherMessageFormatter();
Body = Msg.Body;
但以下内容将失败:
Msg = Queue.Receive();
Queue.Formatter = new MessageFormatter();
因为当队列收到消息时,消息的格式化程序被初始化为队列的当前格式化程序,所以如果队列的格式化程序仅在之后设置,它将无法工作第一条消息已经收到。