MSMQ将失败的MessageBody保存到文本文件

时间:2017-06-08 11:09:00

标签: c# stream msmq

我正在编写Windows服务来监听和处理来自MSMQ的消息。监听器有各种错误处理步骤,但如果所有其他方法都失败了,我想将消息正文保存到文本文件中,以便我可以查看它。但是,当这个条件被发现时,我似乎无法提取我的消息内容。下面的代码是相关部分的简单表示,它总是生成一个空文本文件,即使我知道我测试的消息不是空的。但是,如果我注释掉反序列化XML的初始尝试,则故障安全确实有效,并生成带有消息体的文本文件。所以我认为问题与反序列化尝试如何离开底层流有关?只是为了澄清,当消息包含可以反序列化的有效XML时,服务一切正常,故障安全永远不会发挥作用。

        MyClass myClass = null;

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

            // Comment the following out and the fail safe works
            // Let this run and fail and the text file below is always empty
            myClass = (MyClass)serializer.Deserialize(m.BodyStream);
        }
        catch (Exception ex)
        {

        }

        if (myClass == null)
        {
            string filePath = @"D:\path\file.txt";

            m.Formatter = new ActiveXMessageFormatter();

            StreamReader reader = new StreamReader(m.BodyStream);

            File.WriteAllText(filePath, reader.ReadToEnd());
        }

1 个答案:

答案 0 :(得分:0)

取决于您使用的格式化程序:

对于Windows二进制消息:

File.WriteAllText(<path>, (new UTF8Encoding()).GetString((byte[])msg.Body)); // for binary

对于XML消息,请尝试:

msg.Formatter = new XmlMessageFormatter(new String[] { "System.String, mscorlib" });
var text = msg.Body.ToString(); 
// write to file..

对于二进制或XML,请使用本机格式化程序:

msg.Formatter = new ActiveXMessageFormatter();
reader = new StreamReader(msg.BodyStream);
msgBody = reader.ReadToEnd();
// write to file..