当前位置:   article > 正文

C# 启动/停止 iis 网站 例子源码(iis 6.0下测试通过)_c# 实现web站点启动和停止

c# 实现web站点启动和停止

这里写图片描述

      #region IIS启动/停止
        private enum eStates
        {
            Start = 2,
            Stop = 4,
            Pause = 6,
        }
        private string lastWebsite;

        private string websiteHash
        {
            get
            {
                return string.Format("{0}:{1}:{2}", txtServer.Text, txtUserID.Text, txtPassword.Text);
            }
        }
        private void initWebsiteList()
        {
            if (websiteHash == lastWebsite)
                return;
            lastWebsite = websiteHash;
            Cursor saveCursor = Cursor;
            Cursor = Cursors.WaitCursor;
            cmbWebsites.Items.Clear();
            cmbWebsites.Items.AddRange(enumerateSites());
            if (cmbWebsites.Items.Count > 0)
                cmbWebsites.SelectedIndex = 0;
            Cursor = saveCursor;
        }
        /// <summary>
        /// 定义开始”或“停止”,当前选择的网站上设置状态
        /// </summary>
        /// <param name="state"></param>
        private void siteInvoke(eStates state)
        {
            string site = getSiteIdByName(cmbWebsites.SelectedItem.ToString());

            if (site == null)
            {
                // on the odd chance that someone removed the website since we
                // enumerated the list
                MessageBox.Show("Website '" + cmbWebsites.SelectedItem + "' not found", "Can't " + state + " website");
                showStatus(site);
                return;
            }
            lblSite.Text = site;

            try
            {
                ConnectionOptions connectionOptions = new ConnectionOptions();

                if (txtUserID.Text.Length > 0)
                {
                    connectionOptions.Username = txtUserID.Text;
                    connectionOptions.Password = txtPassword.Text;
                }
                else
                {
                    connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
                }

                ManagementScope managementScope =
                    new ManagementScope(@"\\" + txtServer.Text + @"\root\microsoftiisv2", connectionOptions);

                managementScope.Connect();
                if (managementScope.IsConnected == false)
                {
                    MessageBox.Show("Could not connect to WMI namespace " + managementScope.Path, "Connect Failed");
                }
                else
                {
                    SelectQuery selectQuery =
                        new SelectQuery("Select * From IIsWebServer Where Name = 'W3SVC/" + site + "'");
                    using (ManagementObjectSearcher managementObjectSearcher =
                            new ManagementObjectSearcher(managementScope, selectQuery))
                    {
                        foreach (ManagementObject objMgmt in managementObjectSearcher.Get())
                            objMgmt.InvokeMethod(state.ToString(), new object[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.ToString().Contains("Invalid namespace"))
                {
                    MessageBox.Show("Invalid Namespace Exception" + Environment.NewLine + Environment.NewLine +
                                    "This program only works with IIS 6 and later", "Can't " + state + " website");
                }
                else
                {
                    MessageBox.Show(ex.Message, "Can't " + state + " website");
                }
            }
            showStatus(site);
        }
        /// <summary>
        /// 通过siteId找到指定的网站名称
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        private string getSiteIdByName(string siteName)
        {
            DirectoryEntry root = getDirectoryEntry("IIS://" + txtServer.Text + "/W3SVC");
            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {
                    if (e.Properties["ServerComment"].Value.ToString().Equals(siteName, StringComparison.OrdinalIgnoreCase))
                    {
                        return e.Name;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 返回一个字符串数组中可用的网站名称
        /// </summary>
        /// <returns></returns>
        private string[] enumerateSites()
        {
            List<string> siteNames = new List<string>();
            try
            {
                DirectoryEntry root = getDirectoryEntry("IIS://" + txtServer.Text + "/W3SVC");
                foreach (DirectoryEntry e in root.Children)
                {
                    if (e.SchemaClassName == "IIsWebServer")
                    {
                        siteNames.Add(e.Properties["ServerComment"].Value.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Can't enumerate websites");
                lastWebsite = null;
                txtServer.Focus();
                txtServer.SelectAll();
            }
            return siteNames.ToArray();
        }
        /// <summary>
        /// 按名称查找一个网站的显示和更新站点ID和地位
        /// </summary>
        /// <param name="siteName"></param>
        private void findWebsite(string siteName)
        {
            string site = getSiteIdByName(siteName);
            if (site == null)
            {
                MessageBox.Show("Website '" + siteName + "' not found", "Error");
                showStatus(site);
                return;
            }
            lblSite.Text = site;
            showStatus(site);
        }
        /// <summary>
        /// 显示指定站点的运行/停止状态ID
        /// </summary>
        /// <param name="siteId"></param>
        private void showStatus(string siteId)
        {
            string result = "unknown";
            DirectoryEntry root = getDirectoryEntry("IIS://" + txtServer.Text + "/W3SVC/" + siteId);
            PropertyValueCollection pvc;
            pvc = root.Properties["ServerState"];
            if (pvc.Value != null)
                result = (pvc.Value.Equals((int)eStates.Start) ? "Running" :
                          pvc.Value.Equals((int)eStates.Stop) ? "Stopped" :
                          pvc.Value.Equals((int)eStates.Pause) ? "Paused" :
                          pvc.Value.ToString());
            lblStatus.Text = result + " (" + pvc.Value + ")";
        }
        /// <summary>
        /// 返回一个DirectoryEntry对象路径使用可选的用户id和密码
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private DirectoryEntry getDirectoryEntry(string path)
        {
            if (txtUserID.Text.Length > 0)
                return new DirectoryEntry(path, txtUserID.Text, txtPassword.Text);
            else
                return new DirectoryEntry(path);
        }
        /// <summary>
        /// 设置ID和选择网站的地位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbWebsites_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            findWebsite(cmbWebsites.SelectedItem.ToString());
        }
        private void cmbWebsites_Enter_1(object sender, EventArgs e)
        {
            initWebsiteList();
        }
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            siteInvoke(eStates.Start);
        }
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            siteInvoke(eStates.Stop);
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/252363
推荐阅读
相关标签
  

闽ICP备14008679号