Code
下面这个类可以用来直接操作MSMQ,但有一个需要注意的是,如果你是用APS.NET或WINDOWS SERVICE 操作MSMQ
一定要记的把MSMQ的队列权限设成everyone完全控制,不然会访问不了.我的程序中也增加了对这个权限的控制
mq.SetPermissions("Everyone", MessageQueueAccessRights.FullControl); //这一句就够了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Messaging;
namespace SNET.Common
{
    /// <summary>
    /// 
    /// </summary>
    public class MSMQHelper
    {

/// <summary>
        /// 通过Create方法创建使用指定路径的新消息队列
        /// </summary>
        /// <param name="queuePath"></param>
        public static void Createqueue(string queuePath)
        {
            try
            {
                if (!MessageQueue.Exists(queuePath))
                {
                    MessageQueue mq = MessageQueue.Create(queuePath,true);
                    if (mq != null)
                    {
                        mq.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
                    }
                }              
            }
            catch (MessageQueueException e)
            {
                throw new Exception(e.ToString());
            }
        }
        /// <summary>
        /// Sends the message.
        /// </summary>
        public static void SendMessage(string queuePath,string strBody)
        {
            MessageQueue myQueue = null;
            try
            {
                //连接到本地的队列
                myQueue = new MessageQueue(queuePath);
                Message myMessage = new Message();
                myMessage.Body = strBody;
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                //发送消息到队列中
                myQueue.Send(myMessage);
                myQueue.Dispose();
            }
            catch (ArgumentException e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if (myQueue != null)
                    myQueue.Dispose();
            }
        }
        /// <summary>
        /// Sends the message.
        /// </summary>
        public static void SendMessage(string queuePath, string queueLable,string strBody)
        {
            MessageQueue myQueue = null;
            try
            {
                //连接到本地的队列
                myQueue = new MessageQueue(queuePath);
                Message myMessage = new Message();
                myMessage.Body = strBody;
                if (queueLable != null)
                {
                    myMessage.Label = queueLable;
                }
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                //发送消息到队列中
                myQueue.Send(myMessage);
                myQueue.Dispose();
            }
            catch (ArgumentException e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if (myQueue != null)
                    myQueue.Dispose();
            }
        }
        /// <summary>
        /// Receives the message.
        /// </summary>
        /// <param name="QueuePath">The queue path.</param>
        /// <returns></returns>
        public static string ReceiveMessage(string QueuePath)
        {            
            //连接到本地队列
            MessageQueue myQueue = new MessageQueue(QueuePath);
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            try
            {
                //从队列中接收消息
                Message myMessage = myQueue.Receive(new TimeSpan(0,0,6));                
                string context = (string)myMessage.Body; //获取消息的内容
                return context;

}
            catch (MessageQueueException e)
            {
                throw new Exception(e.ToString());
            }
            catch (InvalidCastException e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if (myQueue != null) 
                myQueue.Dispose();
            }
            return "";
        }
        /// <summary>
        /// Clears the message.
        /// </summary>
        /// <param name="QueuePath">The queue path.</param>
        public static void ClearAllMessage(string QueuePath)
        {
            MessageQueue myQueue = null;
            try
            {
                myQueue = new MessageQueue(QueuePath);
                myQueue.Purge();
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if(myQueue != null)
                myQueue.Dispose();
            }
        }
        /// <summary>
        /// Clears the message.
        /// </summary>
        /// <param name="QueuePath">The queue path.</param>
        public static void DeleteMessage(string QueuePath)
        {          
            try
            {               
                MessageQueue.Delete(QueuePath);
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.ToString());
            }     
        }
        /// <summary>
        /// Gets all message.
        /// </summary>
        /// <param name="QueuePath">The queue path.</param>
        /// <returns></returns>
        public static List<string> GetAllMessage(string QueuePath)
        {
            MessageQueue myQueue = null;
            try
            {
                //连接到本地队列
                myQueue = new MessageQueue(QueuePath);
                Message[] message = myQueue.GetAllMessages();
                XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                List<string> msg = new List<string>(message.Length);
                for (int i = 0; i < message.Length; i++)
                {
                    message[i].Formatter = formatter;
                    msg.Add(message[i].Body.ToString());
                }
                return msg;
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (myQueue != null)
                {
                    myQueue.Dispose();
                }
            }
        }
        /// <summary>
        /// Gets all message by enumerator.
        /// </summary>
        /// <param name="QueuePath">The queue path.</param>
        /// <returns></returns>
        public static List<string> GetAllMessageByEnumerator(string QueuePath)
        {
            List<string> msgs = null;
            MessageQueue myQueue = null;
            try
            {
                //连接到本地队列
                myQueue = new MessageQueue(QueuePath);              
                XmlMessageFormatter formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                MessageEnumerator enumerator = myQueue.GetMessageEnumerator();
                msgs = new List<string>();
                while (enumerator.MoveNext())
                {
                    Message content = (Message)enumerator.Current;
                    content.Formatter = formatter;
                    msgs.Add(content.Body.ToString());
                    enumerator.RemoveCurrent();
                }
                
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (myQueue != null)
                {
                    myQueue.Dispose();
                }
            }
            return msgs;
        }
    }
}

转载于:https://www.cnblogs.com/bobofsj11/archive/2009/09/02/1558568.html

.Net 操作MSMQ相关推荐

  1. WCF4.0新特性体验(9):非破坏性队列消息接收(Non-destructive queue receive )

    这次来介绍一下WCF4.0新特性体验(9):非破坏性队列接收(Non-destructive queue receive ).这个特性不是那么直观.确切来说是WCF4.0对于以前处理MSMQ消息队列机 ...

  2. 关于大型网站技术演进的思考

    关于大型网站技术演进的思考(一)--存储的瓶颈(1) 前不久公司请来了位互联网界的技术大牛跟我们做了一次大型网站架构的培训,两天12个小时信息量非常大,知识的广度和难度也非常大,培训完后我很难完整理出 ...

  3. MSMQ(Microsoft Message Queue)介绍

    利用 MSMQ(Microsoft Message Queue),应用程序开发人员可以通过发送和接收消息方便地与应用程序进行快速可靠的通信.消息处理为您提供了有保障的消息传递和执行许多业务处理的可靠的 ...

  4. Redis学习笔记~实现消息队列比MSMQ更方便

    回到目录 什么是队列:简单的说就是数据存储到一个空间里(可以是内存,也可以是物理文件),先存储的数据对象,先被取出来,这与堆栈正好相反,消息队列也是这样,将可能出现高并发的数据进行队列存储,并按着入队 ...

  5. WCF 4.0 进阶系列 – 第十二章 实现单向操作和异步操作(下)

    使用消息队列 消息队列是本书WCF异步技术中的最后一个出场的.消息队列可以为消息传输提供持久性.可靠性和事务性.甚至,发送消息的客户端程序与接受消息的服务可以不必同时运行.但使用该灵活性需要付出一定的 ...

  6. 使用VMware桥接模式组建局域网测试MSMQ(二)

    上一篇讲了搭建VMware虚拟机实现与宿主机相互通信,环境已经就绪,现在就可以做MSMQ的分布式开发了. 本篇准备分四点介绍MSMQ: 1.MSMQ简介 2.MSMQ的安装 3.MSMQ编程开发 4. ...

  7. 浅析Microsoft .net PetShop程序中的购物车和订单处理模块(Profile技术,异步MSMQ消息)转...

    对于Microsoft .net PetShop程序中的购物车和订单处理模块,文中主要分析两种技术的应用: 1. Profile技术在PetShop程序中用于三处: 1) 购物车ShoppingCar ...

  8. 我的WCF之旅(12):使用MSMQ进行Reliable Messaging(转载)

    一.为什么要使用MSMQ 在一个分布式的环境中,我们往往需要根据具体的 情况采用不同的方式进行数据的传输.比如在一个Intranet内,我们一般通过TCP进行高效的数据通信:而在一个Internet的 ...

  9. 简单易用的.NET免费开源RabbitMQ操作组件EasyNetQ解析

    对于目前大多的.NET项目,其实使用的技术栈都是差不多,估计现在很少用控件开发项目的了,毕竟一大堆问题.对.NET的项目,目前比较适合的架构ASP.NET MVC,ASP.NET WebAPI,ORM ...

最新文章

  1. linux ubuntu 获取仓库源码并构建
  2. php实现最大公约数,php求最大公约数
  3. hdu 4277 USACO ORZ
  4. 如何用MaskBlt实现两个位图的合并,从而实现背景透明
  5. java同事不写泛型_跳了一次JAVA泛型擦除的坑
  6. [最全操作指南] 在线六个项目全部迁移Linux
  7. JSF基于事件的沟通:过时的方法
  8. GY歌谣之读懂每行代码(飞智) 2020 10 16 Duplicate keys detected
  9. 垃圾回收算法_垃圾回收算法有哪些
  10. 电商网站交易记录设计
  11. 惠普HP LaserJet 1160 驱动
  12. 水经注地图下载器注册机机器码过长_微图影像下载参数说明
  13. 测试用例设计方法——等价类划分法
  14. jflash添加芯片_Jflash用于烧录
  15. 智能化监狱室内人员定位管理系统,RFID室内定位方案更加智能-新导智能
  16. adobe animate2022动画制作软件
  17. 随机森林树的特点--摘抄笔记
  18. Go学习笔记 一篇到底
  19. 电脑常见问题之-右键无新建文件夹选项
  20. WGCLOUD和ZABBIX有什么不一样

热门文章

  1. matlab p-tite分割图像,P'tite fourmi
  2. alfs学习笔记-自动化构建lfs系统
  3. linux两台服务器之间文件/文件夹拷贝
  4. 将两个有序链表合并,合并后仍然有序
  5. web开发快速提高工作效率的一些资源
  6. (转) Java线程同步阻塞, sleep(), suspend(), resume(), yield(), wait(), notify()
  7. ionic一些常见问题及方法
  8. Struts2-2.了解struts.xml的查找顺序
  9. Android学习笔记之使用百度地图实现地图控制
  10. 嵌入式linux和嵌入式android系统有什么区别和联系?