2011-01-26 67 views
2

是否可以直接從隊列中讀取消息作爲字符串(與從計算機查看MSMQ消息時看到的消息體相同管理MSC管理單元),以便我可以將它自己保存到數據庫中?我希望能夠在不丟失任何數據的情況下將其存儲起來,並且我擔心如果反序列化/序列化它,我可能會失去一些東西。如何從隊列中讀取MSMQ消息對象作爲消息體的字符串

+0

你只關心保存郵件正文並沒有其他消息屬性? – 2011-01-28 01:40:53

回答

3

試試這個..

string QueueName = @".\private$\publishingQueue"; 

//note, you cannot use method exists on remote queues 

if (MessageQueue.Exists(QueueName)) 
{ 

var queue = new MessageQueue(queueInfo.QueueName) 
{ 
MessageReadPropertyFilter = new MessagePropertyFilter 
{ 
     ArrivedTime = true, 
     Body = true 
    } 
}; 


var messages = queue.GetAllMessages(); 
var m = messages[0]; 
m.Formatter = new System.Messaging.XmlMessageFormatter(new String[] {}); 

StreamReader sr = new StreamReader(m.BodyStream); 

string ms = ""; 
string line; 

while (sr.Peek() >= 0) 
{ 
     ms += sr.ReadLine(); 
} 

//ms now contains the message  
}