Udostępnij za pośrednictwem


Sample code to save as MSMQ messages from outgoing queues to files

The following code will read messages from outoging queues and then create folder structure as \domain or server name or IP\private$ or (public)\queue name to save the messages as .xml files.

The reference is the sample from codeproject: https://www.codeproject.com/Articles/22847/Accessing-Outgoing-Message-Queues-MSMQ private void SaveMessages(string queueFormatName, int numOfMessagesToRead) { MSMQ.MSMQQueueInfo info = new MSMQ.MSMQQueueInfo(); info.FormatName = queueFormatName; MSMQ.MSMQQueue mq = info.Open((int)(MSMQ.MQACCESS.MQ_ADMIN_ACCESS | MSMQ.MQACCESS.MQ_PEEK_ACCESS), (int)MSMQ.MQSHARE.MQ_DENY_NONE); for (int i = 0; i < numOfMessagesToRead; i++) { object wantdest = false; object tr = true; object num = 0; MSMQ.MSMQMessage msg = null; try{ if (i == 0) msg = mq.PeekCurrent(ref wantdest, ref tr, ref num, ref wantdest); //Peek(ref wantdest, ref tr, ref num, ref wantdest); else msg = mq.PeekNext(ref wantdest, ref tr, ref num, ref wantdest); } catch (Exception ee) { //MessageBox.Show(ee.ToString()); } if (msg == null) { WriteLine("Number of Messages to read:" + (numOfMessagesToRead - i).ToString() + " msg is null."); continue; } //ASCIIEncoding encoding = new ASCIIEncoding(); UTF8Encoding utf8encoding = new UTF8Encoding(); string queuePathName = queueFormatName.Substring(queueFormatName.IndexOf(":")+1); string path = Directory.GetCurrentDirectory(); path += "\\SavedMessages\\" + queuePathName; //MessageBox.Show(path); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } byte[] guid = new byte[16]; byte[] seq = new byte[4]; Array.Copy((byte[])msg.Id, 0, guid, 0, 16); Array.Copy((byte[])msg.Id, 16, seq, 0, 4); int seqNumber = BitConverter.ToInt32(seq, 0); Guid msgId = new Guid(guid); path += "\\" + msgId.ToString() + "_" + seqNumber.ToString() + ".xml"; //MessageBox.Show(path); try { File.WriteAllText(path, utf8encoding.GetString((byte[])msg.Body)); } catch (Exception ee) { File.WriteAllText(path, (string)msg.Body); //MessageBox.Show(ee.ToString()); } } }

Best regards,
WenJun Zhang