IISManager.cs 2.5 KB
using System;
using System.DirectoryServices;

namespace ServiceManager
{
	/// <summary>
	/// IISManager ժҪ˵
	/// </summary>
	public class IISManager
	{
		/// <summary>
		///		Default constructor uses localhost as default server
		/// </summary>
		public IISManager()
		{
			_serverName = "localhost";
		}

		/// <summary>
		///		Constructor
		/// </summary>
		/// <param name="serverName">Name of the IIS Server</param>
		public IISManager(string serverName)
		{
			_serverName = serverName;
		}

		/// <summary>
		///		Connect to IISServer
		/// </summary>
		public void Connect()
		{
			try
			{
				_iisServer = new DirectoryEntry("IIS://" + _serverName + "/W3SVC/1");
			}
			catch (Exception e)
			{
				throw new Exception("޷: " + _serverName,e);
			}
		}

		/// <summary>
		///		Create a virtual directory
		/// </summary>
		/// <param name="nameDirectory">Name of the new virtual directory</param>
		/// <param name="realPath">Path of the directory</param>
		public bool CreateVirtualDirectory(string nameDirectory,string realPath)
		{	
			DirectoryEntry folderRoot = _iisServer.Children.Find("Root",VirDirSchemaName);
			try
			{
				DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory,VirDirSchemaName);
				newVirDir.CommitChanges();
				// Set Properties
				newVirDir.Properties["AccessRead"].Add(true);
				newVirDir.Properties["Path"].Value = realPath;
				// Create a Application
				newVirDir.Invoke("AppCreate",true);
				// Save Changes
				newVirDir.CommitChanges();
				folderRoot.CommitChanges();
				_iisServer.CommitChanges();
			}
			catch
			{
				return false;
			}
			return true;
		}

		/// <summary>
		///		Delete a virtual directory
		/// </summary>
		/// <param name="nameDirectory">Name of the delete virtual directory</param>
		public bool DeleteVirtualDirectory(string nameDirectory)
		{	
			DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC/1/Root");
			try
			{
				DirectoryEntry deVirDir = folderRoot.Children.Find(nameDirectory,VirDirSchemaName); 

				folderRoot.Children.Remove(deVirDir);

				folderRoot.CommitChanges();
				_iisServer.CommitChanges();

			}
			catch
			{
				//throw new Exception(e.Message,e);
				return false;
			}
			return true;
		}
	
	#region Properties
		public string ServerName
		{
			get
			{
				return _serverName;
			}
			set
			{
				_serverName = value;
			}
		}
	#endregion
	
		public static string VirDirSchemaName = "IIsWebVirtualDir";
	
	#region Private Members	
		private string _serverName;
		private DirectoryEntry _iisServer;
	#endregion

	}
}