C # operation of IIS program pool and site creation configuration implementation code

Source: Internet
Author: User

First, you must reference Microsoft. Web. Administration, which is mainly used to operate IIS7;

Using System. DirectoryServices;
Using Microsoft. Web. Administration;

1: configure the current version of IIS:

Copy codeThe Code is as follows: DirectoryEntry getEntity = new DirectoryEntry ("IIS: // localhost/W3SVC/INFO ");
String Version = getEntity. Properties ["MajorIISVersionNumber"]. Value. ToString ();
MessageBox. Show ("IIS Version:" + Version );

2: determines whether the program pool exists;

Copy codeThe Code is as follows: // <summary>
/// Determine whether the program pool exists
/// </Summary>
/// <Param name = "AppPoolName"> program pool name </param>
/// <Returns> true: false does not exist </returns>
Private bool IsAppPoolName (string AppPoolName)
{
Bool result = false;
DirectoryEntry appPools = new DirectoryEntry ("IIS: // localhost/W3SVC/AppPools ");
Foreach (DirectoryEntry getdir in appPools. Children)
{
If (getdir. Name. Equals (AppPoolName ))
{
Result = true;
}
}
Return result;
}

3. Delete the application pool.

Copy codeThe Code is as follows: // <summary>
/// Delete the specified program pool
/// </Summary>
/// <Param name = "AppPoolName"> program pool name </param>
/// <Returns> true: Deletion successful; false: deletion failed </returns>
Private bool DeleteAppPool (string AppPoolName)
{
Bool result = false;
DirectoryEntry appPools = new DirectoryEntry ("IIS: // localhost/W3SVC/AppPools ");
Foreach (DirectoryEntry getdir in appPools. Children)
{
If (getdir. Name. Equals (AppPoolName ))
{
Try
{
Getdir. DeleteTree ();
Result = true;
}
Catch
{
Result = false;
}
}
}
Return result;
}

4: Create an application pool (the application pool is mainly set for IIS7; The IIS7 application pool hosting mode mainly includes integration and classic mode, and the NET version setting)

Copy codeThe Code is as follows: string AppPoolName = "LamAppPool ";
If (! IsAppPoolName (AppPoolName ))
{
DirectoryEntry newpool;
DirectoryEntry appPools = new DirectoryEntry ("IIS: // localhost/W3SVC/AppPools ");
Newpool = appPools. Children. Add (AppPoolName, "IIsApplicationPool ");
Newpool. CommitChanges ();
MessageBox. Show (AppPoolName + "program pool added successfully ");
}
# Endregion

# Region modify application configurations (including managed Mode and Its NET Running version)
ServerManager sm = new ServerManager ();
Sm. ApplicationPools [AppPoolName]. ManagedRuntimeVersion = "v4.0 ";
Sm. ApplicationPools [AppPoolName]. ManagedPipelineMode = ManagedPipelineMode. Classic; // The managed mode is Integrated.
Sm. CommitChanges ();
MessageBox. show (AppPoolName + "program pool managed pipeline mode:" + sm. applicationPools [AppPoolName]. managedPipelineMode. toString () + "Running NET version:" + sm. applicationPools [AppPoolName]. managedRuntimeVersion );

Use the C # code to modify the pipeline mode and version of The IIS7 program pool;

5: Set IIS6 for the NET version. Because NET4.0 is used here, V4.0.30319 and NET2.0 is used here to modify v2.0.50727.

Copy codeThe Code is as follows: // start the aspnet_regiis.exe Program
String fileName = Environment. GetEnvironmentVariable ("windir") + @ "\ Microsoft. NET \ Framework \ v4.0.30319 \ aspnet_regiis.exe ";
ProcessStartInfo startInfo = new ProcessStartInfo (fileName );
// Process the directory path
String path = vdEntry. Path. ToUpper ();
Int index = path. IndexOf ("W3SVC ");
Path = path. Remove (0, index );
// Start the aspnet_iis.exe program and refresh the script ing.
StartInfo. Arguments = "-s" + path;
StartInfo. WindowStyle = ProcessWindowStyle. Hidden;
StartInfo. UseShellExecute = false;
StartInfo. CreateNoWindow = true;
StartInfo. RedirectStandardOutput = true;
StartInfo. RedirectStandardError = true;
Process process = new Process ();
Process. StartInfo = startInfo;
Process. Start ();
Process. WaitForExit ();
String errors = process. StandardError. ReadToEnd ();

6: we may have to increase the MIME type in IIS. The following two types are used: xaml and xap.

Copy codeThe Code is as follows: IISOle. MimeMapClass NewMime = new IISOle. MimeMapClass ();
NewMime. Extension = ". xaml"; NewMime. MimeType = "application/xaml + xml ";
IISOle. MimeMapClass TwoMime = new IISOle. MimeMapClass ();
TwoMime. Extension = ". xap"; TwoMime. MimeType = "application/x-silverlight-app ";
RootEntry. Properties ["MimeMap"]. Add (NewMime );
RootEntry. Properties ["MimeMap"]. Add (TwoMime );
RootEntry. CommitChanges ();

7: The following is a piece of code for IIS operations during installation; compatible with IIS6 and IIS7; create a virtual directory and set the corresponding properties; create a program in the program pool for IIS7 and configure the program pool;

Copy codeThe Code is as follows: // <summary>
/// Create a website
/// </Summary>
/// <Param name = "siteInfo"> </param>
Public void CreateNewWebSite (NewWebSiteInfo siteInfo)
{
If (! EnsureNewSiteEnavaible (siteInfo. BindString ))
{
Throw new Exception ("This website already exists" + Environment. NewLine + siteInfo. BindString );
}
DirectoryEntry rootEntry = GetDirectoryEntry (entPath );

NewSiteNum = GetNewWebSiteID ();
DirectoryEntry newSiteEntry = rootEntry. Children. Add (newSiteNum, "IIsWebServer ");
NewSiteEntry. CommitChanges ();

NewSiteEntry. Properties ["ServerBindings"]. Value = siteInfo. BindString;
NewSiteEntry. Properties ["ServerComment"]. Value = siteInfo. CommentOfWebSite;
NewSiteEntry. CommitChanges ();
DirectoryEntry vdEntry = newSiteEntry. Children. Add ("root", "IIsWebVirtualDir ");
VdEntry. CommitChanges ();
String ChangWebPath = siteInfo. WebPath. Trim (). Remove (siteInfo. WebPath. Trim (). LastIndexOf ('\'), 1 );
VdEntry. Properties ["Path"]. Value = ChangWebPath;

VdEntry. Invoke ("AppCreate", true); // create an application

VdEntry. Properties ["AccessRead"] [0] = true; // set the read permission
VdEntry. Properties ["AccessWrite"] [0] = true;
VdEntry. Properties ["AccessScript"] [0] = true; // execution permission
VdEntry. Properties ["AccessExecute"] [0] = false;
VdEntry. Properties ["DefaultDoc"] [0] = "Login. aspx"; // set the default document
VdEntry. Properties ["AppFriendlyName"] [0] = "LabManager"; // Application name
VdEntry. Properties ["AuthFlags"] [0] = 1; // 0 indicates that anonymous access is not allowed. 1 indicates that 3 is basic authentication and 7 is windows inherited authentication.
VdEntry. CommitChanges ();

// Add MIME for the operation
// IISOle. MimeMapClass NewMime = new IISOle. MimeMapClass ();
// NewMime. Extension = ". xaml"; NewMime. MimeType = "application/xaml + xml ";
// IISOle. MimeMapClass TwoMime = new IISOle. MimeMapClass ();
// TwoMime. Extension = ". xap"; TwoMime. MimeType = "application/x-silverlight-app ";
// RootEntry. Properties ["MimeMap"]. Add (NewMime );
// RootEntry. Properties ["MimeMap"]. Add (TwoMime );
// RootEntry. CommitChanges ();

# Region for IIS7
DirectoryEntry getEntity = new DirectoryEntry ("IIS: // localhost/W3SVC/INFO ");
Int Version = int. Parse (getEntity. Properties ["MajorIISVersionNumber"]. Value. ToString ());
If (Version> 6)
{
# Region create an application pool
String AppPoolName = "LabManager ";
If (! IsAppPoolName (AppPoolName ))
{
DirectoryEntry newpool;
DirectoryEntry appPools = new DirectoryEntry ("IIS: // localhost/W3SVC/AppPools ");
Newpool = appPools. Children. Add (AppPoolName, "IIsApplicationPool ");
Newpool. CommitChanges ();
}
# Endregion

# Region modify application configurations (including managed Mode and Its NET Running version)
ServerManager sm = new ServerManager ();
Sm. ApplicationPools [AppPoolName]. ManagedRuntimeVersion = "v4.0 ";
Sm. ApplicationPools [AppPoolName]. ManagedPipelineMode = ManagedPipelineMode. Classic; // The managed mode is Integrated.
Sm. CommitChanges ();
# Endregion

VdEntry. Properties ["AppPoolId"]. Value = AppPoolName;
VdEntry. CommitChanges ();
}
# Endregion

// Start the aspnet_regiis.exe Program
String fileName = Environment. GetEnvironmentVariable ("windir") + @ "\ Microsoft. NET \ Framework \ v4.0.30319 \ aspnet_regiis.exe ";
ProcessStartInfo startInfo = new ProcessStartInfo (fileName );
// Process the directory path
String path = vdEntry. Path. ToUpper ();
Int index = path. IndexOf ("W3SVC ");
Path = path. Remove (0, index );
// Start the aspnet_iis.exe program and refresh the script ing.
StartInfo. Arguments = "-s" + path;
StartInfo. WindowStyle = ProcessWindowStyle. Hidden;
StartInfo. UseShellExecute = false;
StartInfo. CreateNoWindow = true;
StartInfo. RedirectStandardOutput = true;
StartInfo. RedirectStandardError = true;
Process process = new Process ();
Process. StartInfo = startInfo;
Process. Start ();
Process. WaitForExit ();
String errors = process. StandardError. ReadToEnd ();
If (errors! = String. Empty)
{
Throw new Exception (errors );
}

}

Copy codeThe Code is as follows: string entPath = String. Format ("IIS: // {0}/w3svc", "localhost ");

Public DirectoryEntry GetDirectoryEntry (string entPath)
{
DirectoryEntry ent = new DirectoryEntry (entPath );
Return ent;
}

Public class NewWebSiteInfo
{
Private string hostIP; // host IP Address
Private string portNum; // The website port number.
Private string descOfWebSite; // indicates the website. Generally, it is the website name. For example, "www.dns.com.cn"
Private string commentOfWebSite; // website comment. It is also the website name of the website.
Private string webPath; // The Home Directory of the website. For example, "e: \ mp"

Public NewWebSiteInfo (string hostIP, string portNum, string descOfWebSite, string commentOfWebSite, string webPath)
{
This. hostIP = hostIP;
This. portNum = portNum;
This. descOfWebSite = descOfWebSite;
This. commentOfWebSite = commentOfWebSite;
This. webPath = webPath;
}

Public string BindString
{
Get
{
Return String. Format ("{0 }:{ 1 }:{ 2}", hostIP, portNum, descOfWebSite); // website ID (IP address, port, Host header value)
}
}

Public string PortNum
{
Get
{
Return portNum;
}
}

Public string CommentOfWebSite
{
Get
{
Return commentOfWebSite;
}
}

Public string WebPath
{
Get
{
Return webPath;
}
}
}

8: The following code sets folder permissions. The following Code creates Everyone and gives all permissions.

Copy codeThe Code is as follows: // <summary>
/// Set folder permissions to grant all permissions to EVERONE
/// </Summary>
/// <Param name = "FileAdd"> folder path </param>
Public void SetFileRole ()
{
String FileAdd = this. Context. Parameters ["installdir"]. ToString ();
FileAdd = FileAdd. Remove (FileAdd. LastIndexOf ('\'), 1 );
DirectorySecurity fSec = new DirectorySecurity ();
FSec. AddAccessRule (new FileSystemAccessRule ("Everyone", FileSystemRights. FullControl, response. ContainerInherit | response. ObjectInherit, PropagationFlags. None, AccessControlType. Allow ));
System. IO. Directory. SetAccessControl (FileAdd, fSec );
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.