实例介绍
【实例截图】
【核心代码】
public partial class WebsiteController : Form
{
#region enumerators and variables
private enum eStates
{
Start = 2,
Stop = 4,
Pause = 6,
}
private string lastWebsite;
#endregion enumerators and variables
#region constructor
public WebsiteController()
{
InitializeComponent();
initWebsiteList();
}
#endregion constructor
#region properties
private string websiteHash
{
get
{
return string.Format("{0}:{1}:{2}",
txtServer.Text, txtUserID.Text, txtPassword.Text);
}
}
#endregion properties
#region private support methods
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>
/// Given an eStates of "Start" or "Stop", set the state on the currently
/// selected website
/// </summary>
/// <param name="state">Either eStates.Stop or eStates.Start to stop or start the website</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>
/// Find the siteId for a specified website name. This assumes that the website's
/// ServerComment property contains the website name.
/// </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>
/// Return a string array of the available website names
/// </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>
/// Lookup a website by name and update the display for the site ID and status
/// </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>
/// Show the running/stopped state for the specified site ID
/// </summary>
/// <param name="siteId">Numeric site ID</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>
/// Return a DirectoryEntry object for path using optional userId and password
/// </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);
}
#endregion private support methods
#region event handlers
/// <summary>
/// Set up ID and status of selected website
/// </summary>
private void cmbWebsites_SelectedIndexChanged(object sender, EventArgs e)
{
findWebsite(cmbWebsites.SelectedItem.ToString());
}
/// <summary>
/// On entry to the websites combobox, fill with enumeration of websites if necessary
/// </summary>
private void cmbWebsites_Enter(object sender, EventArgs e)
{
initWebsiteList();
}
/// <summary>
/// Exit button clicked - goodbye
/// </summary>
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
/// <summary>
/// Attempt to start the selected website
/// </summary>
private void btnStart_Click(object sender, EventArgs e)
{
siteInvoke(eStates.Start);
}
/// <summary>
/// Attempt to stop the selected website
/// </summary>
private void btnStop_Click(object sender, EventArgs e)
{
siteInvoke(eStates.Stop);
}
#endregion event handlers
}
标签: iis
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论