基本信息
源码名称:C# 启动/停止 iis 网站 例子源码(iis 6.0下测试通过)
源码大小:0.01M
文件格式:.zip
开发语言:C#
更新时间:2013-09-08
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
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
}