如何使用C#.Net代码远程重置IIS?

时间:2012-08-06 14:00:19

标签: c# iis windows-server-2008

我在Windows Server 2008上运行IIS服务,我想从我的Windows 7机器重置它。

如何使用C#.Net代码远程重置IIS?

我尝试使用Microsoft.Web.Administration,但它不接受远程服务器详细信息以连接到。可以用于此目的的其他API吗?

1 个答案:

答案 0 :(得分:2)

如果您有特定的网站名称,则可以使用WMI停止并启动该网站。如果它是IIS的整体,我确信IIS WMI提供程序中有一些东西可以做到这一点。在这里,我使用WebAdministration管理IIS下的网站,但也有MicrosoftIISV2。谷歌为WmiExplorer,那里有一些好的。

        var connOptions = new ConnectionOptions();
        connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
        // if you want to connect as someone other than logged in user
        //connOptions.Username = username;
        //connOptions.Password = password;

        var scope = new ManagementScope("\\localhost\WebAdministration", connOptions);

        WqlObjectQuery query = new WqlObjectQuery(`enter code here`string.Format("SELECT * FROM Site WHERE Name = '{0}'", "Default Web Site"));

        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
        {
            foreach (ManagementObject site in searcher.Get())
            {
                ManagementBaseObject inParams = site.GetMethodParameters("Stop");
                site.InvokeMethod("Stop", inParams, null);

                ManagementBaseObject inParams2 = site.GetMethodParameters("Start");
                site.InvokeMethod("Start", inParams2, null);
            }
        }