Start/Stop C# 中使用 WMI 的 BizTalk 发送端口

Start/Stop BizTalk Send port in C# with WMI

是否可以通过 C# start/stop 使用 MSBTS_SendPort class 发送端口?

我使用 Windows WMI 获取了端口详细信息和状态,并尝试 Start/Stop 端口

  public bool CheckSendPorts()
    {
        bool returnValue = true;
        UserName = "";
        Password = "";
        ServerName = "testserver";
        using (ManagementObjectSearcher searcher = GetWmiSearcher(UserName,Password,ServerName, WMI_SCOPE, $"SELECT * FROM MSBTS_SendPort where Name = 'testSendPort'"))
        {
            if (searcher == null)
            {
                //WriteOutput($"No Send Ports found.", true);
                return false;
            }

            foreach (ManagementObject instanceObject in searcher.Get())
            {
                string portName = instanceObject["Name"] as string;
                uint portState = (uint)instanceObject["Status"];
                string portStatus = GetPortStatus((uint)instanceObject["Status"]);
                bool ignoreLocation = false;

                
            }
        }

        return returnValue;
    }

    internal ManagementObjectSearcher GetWmiSearcher(string username,string password,string servername, string wmiScope, string wmiQuery)
    {

        ConnectionOptions connectionOptions = new ConnectionOptions();

        connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;

        if (!string.IsNullOrEmpty(username))
        {
            connectionOptions.Username = username;
            connectionOptions.Password = password;
        }
        else
        {
            connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
        }

        ManagementScope scope = new ManagementScope($@"\{servername}{wmiScope}");
        scope.Options = connectionOptions;

        EnumerationOptions enumOptions = new EnumerationOptions();
        enumOptions.ReturnImmediately = false;

        SelectQuery query = new SelectQuery(wmiQuery);

        return new ManagementObjectSearcher(scope, query, enumOptions);
    }

  private string GetPortStatus(uint code)
    {
        switch (code)
        {
            case 1:
                return "Bound";

            case 2:
                return "Stopped";

            case 3:
                return "Started";

            default:
                return "Unknown";
        }
    }

Microsoft 文档建议有一种方法 MSBTS_SendPort.Stop 可以停止端口。可能吗?

您可以在遍历实例时在 foreach 循环中调用“停止”或“开始”方法。

        foreach (ManagementObject instanceObject in searcher.Get())
        {
            string portName = instanceObject["Name"] as string;
            uint portState = (uint)instanceObject["Status"];
            string portStatus = GetPortStatus((uint)instanceObject["Status"]);
            bool ignoreLocation = false;

            //invoke method stop with an empty object array for parameters (because this method doesn't take any parameters.
            instanceObject.InvokeMethod("stop", new object[]{ });
         
        }