C# 如何设置消息队列的所有者?

C# 如何设置消息队列的所有者?,c#,msmq,C#,Msmq,System.Messaging.MessageQueue类不提供设置队列所有权的方法。如何以编程方式设置MSMQ消息队列的所有者?简短的回答是调用windows api函数 一个完整的类,它定义了System.Messaging.MessageQueue上的SetOwner扩展方法 void SetOwner(MessageQueue queue, byte[] sid, bool ownerDefaulted = false) { var securityDescriptor = n

System.Messaging.MessageQueue类不提供设置队列所有权的方法。如何以编程方式设置MSMQ消息队列的所有者?

简短的回答是调用windows api函数

一个完整的类,它定义了
System.Messaging.MessageQueue
上的
SetOwner
扩展方法

void SetOwner(MessageQueue queue, byte[] sid, bool ownerDefaulted = false)
{
    var securityDescriptor = new Win32.SECURITY_DESCRIPTOR();
    if (!Win32.InitializeSecurityDescriptor(securityDescriptor, Win32.SECURITY_DESCRIPTOR_REVISION))
        throw new Win32Exception();

    if (!Win32.SetSecurityDescriptorOwner(securityDescriptor, sid, ownerDefaulted))
        throw new Win32Exception();

    if (Win32.MQSetQueueSecurity(queue.FormatName, Win32.OWNER_SECURITY_INFORMATION, securityDescriptor))
        throw new Win32Exception();
}