. How to operate IIS in net

Source: Internet
Author: User
Tags foreach bool ftp connect root directory
IIS net has actually done a good job for us in this area. FCL offers a number of classes to help us complete this work, making our development work very simple and enjoyable. Programming to control IIS is actually very simple, like the ASP. NET, you need to use ADSI to manipulate IIS, but at this point we no longer need to getobject this stuff, because. NET provides us with a more powerful new dongdong.
The System.DirectoryServices namespace includes powerful Dongdong--directoryentry,directoryentries that provide us with the power to access the Active Directory, which allows us to manipulate IIS, LDAP , NDS, and Winnt, the function is very powerful bar:

However, we only talk about the control of IIS, in general, we operate IIS is generally the operation of the virtual directory, so I put this as the main content.

First of all, we need to figure out the hierarchy of IIS, and here's a map I found from abroad, which explains the hierarchy of IIS:

[Htmchina:image id=image1|12] [/htmchina:image]
To get a sense of the control syntax of IIS, we have to figure out the hierarchy of IIS metadata (Metabase) on the diagram above. Each node in the graph is called the key, each key can contain one or more values, which are the properties we say, and the keys in the IIS metadata match the elements in IIS, so setting the property values in the metadata affects the settings in IIS. This is the basic idea and core of our programming.

Also understand the concept of schema. It represents the name of the schema in IIS, which can understand the type of key in the IIS metadata, specifically the type of each node. We know that IIS has virtual directories, plain directories, and files, all of which are elements of IIS that distinguish their flags from schemas. For example, the schema of the virtual directory is "IIsVirtualDir", the Ordinary Directory is "Iiswebdir". So when we add and delete directories, IIS knows that we are adding a virtual directory or a normal directory.

Create a virtual directory

DirectoryEntry is a great gift from. NET, his name we know his function--directory entrance. People who have used ADSI know that when we operate iis,winnt these, we also need to provide their path, and when we operate IIS, the path is in the format:

Iis://computername/service/website/directory

ComputerName: That is, the name of the server to operate, can be the name can also be IP, often used is the localhost
Service: That is, the operation of the server, IIS has the Web, also has FTP, as well as SMTP these services, we mainly operate IIS Web functions, so here is "w3svc", if it is ftp should be "MSFTPSVC"
WebSite: An IIS service can include many sites, which are used to set up operations for the site. His value is a number, the default is 1, the default site, and if there are other, then start from 1 and so on.
Directory: Needless to say, the directory name of the operation, the general top-level directory of a site is "ROOT", and other directories are his children (child).
First we get the top-level directory (root directory) of a site:

DirectoryEntry RootFolder = new DirectoryEntry ("Iis://localhost/w3svc/1/root");

If we create this object without an exception, it means that the directory is real.

Let's add a new virtual directory, such as "ASPCN":

DirectoryEntry Newvirdir = RootFolder. Children.add ("ASPCN", "IIsWebVirtualDir");
Newvirdir.invoke ("AppCreate", true);
Newvirdir.commitchanges ();
Rootfolder.commitchanges ();
 

The idea of creating a directory is simple, in a subset of the root directory (RootFolder. Children) to add a record, which uses the Add method in the Directoryentries class, which returns a DirectoryEntry that represents the newly added directory, the first parameter is the name of the virtual directory, The second is the class name of the schema to indicate the type of directory we are adding. Then, using the DirectoryEntry invoke method, call the "AppCreate" method in ADSI to actually create the directory (it doesn't seem to take this step to create a directory success, but for the sake of insurance, let's use it), and finally, call the new, The CommitChanges method of the root directory to confirm this operation.

When creating a new directory, we can also assign values to the attributes of the directory, but my actual combat experience tells me that it is best not to do so, and that if you assign values at creation time, there will be many attributes that cannot be assigned success, such as an important path attribute that represents the real directory. Therefore, the flying knife suggested that it is best to create a directory, and then assign a value, that is, update the directory information.

Update virtual Directory

I am sure you are familiar with IIS, and understand some important settings in IIS, such as readable (AccessRead), writable (AccessWrite), executable (AccessExecute), and so on. These can be achieved by assigning values to the Properties collection of the DirectoryEntry property. Assignments can be done in two ways:

The first is to invoke the Add method of the Properties collection, such as:

Dir. properties["AccessRead"]. ADD (TRUE);

The second is to assign a value to the first index value:

Dir. properties["AccessRead"][0] = true;

Both of these methods are feasible. It depends on your liking.

We still have to determine the target to be assigned before we do the assignment: Here we use the Find method of the Directoryentries class, such as:

DirectoryEntry de = RootFolder. Children.find ("ASPCN", "IIsVirtualDir");

If we find it, we can assign a value. You must take a good look at the assignment, the virtual directory can be more than the attribute value, a lot of checks. : (Too much, flying knives I do not repeat, we go to Microsoft's site to check:)

More commonly used are: Accessread,accesswrite,accessexecute,accessscript,defaultdoc,enabledefaultdoc,path

Delete virtual directory

The way to delete a virtual directory is also simple: Find the virtual directory you want to delete, and then call the AppDelete method.

DirectoryEntry de = RootFolder. Children.find ("ASPCN", "IIsVirtualDir");
De. Invoke ("AppDelete", true);
Rootfolder.commitchanges ();
 

Another way is to invoke the Delete method of the root directory.

Object[] paras = new object[2];
Paras[0] = "IIsWebVirtualDir"; Represents the virtual directory of the operation
PARAS[1] = "ASPCN";
RootFolder. Invoke ("Delete", paras);
Rootfolder.commitchanges ();

Like which kind of depends on the programming habit:)

. How to operate IIS in net (source code)

Using System;
Using System.Data;
Using System.DirectoryServices;
Using System.Collections;
Namespace Aspcn.management
{
<summary>
Summary description of the Iismanager.
</summary>
public class Iismanager
{
Define what needs to be used.
private string _server,_website;
Private Virtualdirectories _virdirs;
protected System.DirectoryServices.DirectoryEntry RootFolder;
private bool _batchflag;
Public Iismanager ()
{
Use localhost by default, that is, access to the local machine
_server = "localhost";
_website = "1";
_batchflag = false;
}
Public Iismanager (String strserver)
{
_server = strserver;
_website = "1";
_batchflag = false;
}
<summary>
Defining Public properties
</summary>

The server property defines the name of the access machine, which can be IP and the computed name
public string Server
{
get{return _server;}
set{_server = value;}
}
Website attribute definition, for a number, for convenience, use string
In general, the first host is 1, the second host is 2, and so on
public string WebSite
{
get{return _website;}
set{_website = value;}
}

The name of the virtual directory
Public Virtualdirectories Virdirs
{
get{return _virdirs;}
set{_virdirs = value;}
}
<summary>
Defining public methods
</summary>

Connecting to a server
public void Connect ()
{
Connecttoserver ();
}
For convenience overload
public void Connect (string strserver)
{
_server = strserver;
Connecttoserver ();
}
For convenience overload
public void Connect (String strserver,string strwebsite)
{
_server = strserver;
_website = Strwebsite;
Connecttoserver ();
}
Determine whether to save this virtual directory
public bool Exists (string strvirdir)
{
Return _virdirs. Contains (Strvirdir);
}
Add a virtual directory
public void Create (VirtualDirectory newdir)
{
String strpath = "iis://" + _server + "/w3svc/" + _website + "/root/" + newdir. Name;
if (!_virdirs. Contains (Newdir. Name) | | _batchflag)
{
Try
{
Add to the children collection of root
DirectoryEntry Newvirdir = RootFolder. Children.add (Newdir. Name, "IIsWebVirtualDir";
Newvirdir.invoke ("AppCreate", true);
Newvirdir.commitchanges ();
Rootfolder.commitchanges ();
And then update the data
Updatedirinfo (Newvirdir,newdir);
}
catch (Exception ee)
{
throw new Exception (EE. ToString ());
}
}
Else
{
throw new Exception ("This virtual directory is already exist.";
}
}
Get a virtual directory
Public VirtualDirectory Getvirdir (string strvirdir)
{
VirtualDirectory tmp = NULL;
if (_virdirs. Contains (Strvirdir))
{
TMP = _virdirs. Find (Strvirdir);
((VirtualDirectory) _virdirs[strvirdir]). flag = 2;
}
Else
{
throw new Exception ("This virtual directory isn't exists";
}
return TMP;
}

Update a virtual directory
public void Update (VirtualDirectory dir)
{
Determine if the virtual directory you want to change exists
if (_virdirs. Contains (dir. Name))
{
DirectoryEntry ode = RootFolder. Children.find (dir. Name, "IIsWebVirtualDir";
Updatedirinfo (Ode,dir);
}
Else
{
throw new Exception ("This virtual directory isn't exists.";
}
}
 
Delete a virtual directory
public void Delete (string strvirdir)
{
if (_virdirs. Contains (Strvirdir))
{
Object[] paras = new object[2];
Paras[0] = "IIsWebVirtualDir"; Represents the virtual directory of the operation
PARAS[1] = Strvirdir;
RootFolder. Invoke ("Delete", paras);
Rootfolder.commitchanges ();
}
Else
{
throw new Exception ("Can" t Delete "+ Strvirdir +", because it isn ' t exists. ";
}
}
Batch Update
public void UpdateBatch ()
{
BatchUpdate (_virdirs);
}
Overload a:-)
public void UpdateBatch (Virtualdirectories VDS)
{
BatchUpdate (VDS);
}
 
<summary>
Private method
</summary>

Connecting to a server
private void Connecttoserver ()
{
String strpath = "iis://" + _server + "/w3svc/" + _website + "/root";
Try
{
This.rootfolder = new DirectoryEntry (strpath);
_virdirs = Getvirdirs (This.rootfolder.Children);
}
catch (Exception e)
{
throw new Exception ("Can" T connect to the server ["+ _server +"] ... ", e);
}
}
Perform bulk update
private void BatchUpdate (Virtualdirectories VDS)
{
_batchflag = true;
foreach (Object item in VDS. Values)
{
VirtualDirectory VD = (virtualdirectory) item;
Switch (Vd.flag)
{
Case 0:
Break
Case 1:
Create (VD);
Break
Case 2:
Update (VD);
Break
}
}
_batchflag = false;
}
Update Dongdong
private void Updatedirinfo (DirectoryEntry de,virtualdirectory VD)
{
De. properties["AnonymousUserName"][0] = VD. AnonymousUserName;
De. properties["AnonymousUserPass"][0] = VD. AnonymousUserPass;
De. properties["AccessRead"][0] = VD. AccessRead;
De. properties["AccessExecute"][0] = VD. AccessExecute;
De. properties["AccessWrite"][0] = VD. AccessWrite;
De. properties["AuthBasic"][0] = VD. AuthBasic;
De. properties["AUTHNTLM"][0] = VD. AUTHNTLM;
De. properties["ContentIndexed"][0] = VD. contentindexed;
De. properties["EnableDefaultDoc"][0] = VD. EnableDefaultDoc;
De. properties["EnableDirBrowsing"][0] = VD. enabledirbrowsing;
De. properties["AccessSSL"][0] = VD. AccessSSL;
De. properties["AccessScript"][0] = VD. AccessScript;
De. properties["DefaultDoc"][0] = VD. DefaultDoc;
De. properties["Path"][0] = VD. Path;
De.commitchanges ();
}

Get the virtual directory collection
Private Virtualdirectories Getvirdirs (Directoryentries des)
{
Virtualdirectories tmpdirs = new Virtualdirectories ();
foreach (DirectoryEntry de in Des)
{
if (DE. schemaClassName = "IIsWebVirtualDir"
{
VirtualDirectory VD = new VirtualDirectory ();
Vd. Name = de. Name;
Vd. AccessRead = (bool) de. properties["AccessRead"][0];
Vd. AccessExecute = (bool) de. properties["AccessExecute"][0];
Vd. AccessWrite = (bool) de. properties["AccessWrite"][0];
Vd. AnonymousUserName = (string) de. properties["AnonymousUserName"][0];
Vd. AnonymousUserPass = (string) de. properties["AnonymousUserName"][0];
Vd. AuthBasic = (bool) de. properties["AuthBasic"][0];
Vd. AUTHNTLM = (bool) de. properties["AUTHNTLM"][0];
Vd. ContentIndexed = (bool) de. properties["ContentIndexed"][0];
Vd. EnableDefaultDoc = (bool) de. properties["EnableDefaultDoc"][0];
Vd. EnableDirBrowsing = (bool) de. properties["enabledirbrowsing"][0];
Vd. AccessSSL = (bool) de. properties["AccessSSL"][0];
Vd. AccessScript = (bool) de. properties["AccessScript"][0];
Vd. Path = (string) de. properties["Path"][0];
Vd.flag = 0;
Vd. DefaultDoc = (string) de. properties["DefaultDoc"][0];
Tmpdirs. ADD (VD. NAME,VD);
}
}
return tmpdirs;
}

}
<summary>
VirtualDirectory class
</summary>
public class VirtualDirectory
{
private bool _read,_execute,_script,_ssl,_write,_authbasic,_authntlm,_indexed,_endirbrow,_endefaultdoc;
private string _ausername,_auserpass,_name,_path;
private int _flag;
private string _defaultdoc;
<summary>
Constructors
</summary>
Public VirtualDirectory ()
{
SetValue ();
}
Public VirtualDirectory (String strvirdirname)
{
_name = Strvirdirname;
SetValue ();
}
private void SetValue ()
{
_read = True;_execute = False;_script = False;_ssl= false;_write=false;_authbasic=false;_authntlm=false;
_indexed = False;_endirbrow=false;_endefaultdoc = false;
_flag = 1;
_defaultdoc = "default.htm,default.aspx,default.asp,index.htm";
_path = "c:\\";
_ausername = ""; _auserpass = ""; _name= "";
}
<summary>
Define attributes, IIsVirtualDir too many attributes
I've only got something more important, the others need to add it.
</summary>

public int Flag
{
get{return _flag;}
set{_flag = value;}
}
public bool AccessRead
{
get{return _read;}
set{_read = value;}
}
public bool AccessWrite
{
get{return _write;}
set{_write = value;}
}
public bool AccessExecute
{
get{return _execute;}
set{_execute = value;}
}
public bool AccessSSL
{
get{return _SSL;}
set{_ssl = value;}
}
public bool AccessScript
{
get{return _script;}
set{_script = value;}
}
public bool AuthBasic
{
get{return _authbasic;}
set{_authbasic = value;}
}
public bool AUTHNTLM
{
get{return _AUTHNTLM;}
set{_AUTHNTLM = value;}
}
public bool ContentIndexed
{
get{return _indexed;}
set{_indexed = value;}
}
public bool EnableDirBrowsing
{
get{return _endirbrow;}
set{_endirbrow = value;}
}
public bool EnableDefaultDoc
{
get{return _endefaultdoc;}
set{_endefaultdoc = value;}
}
public string Name
{
get{return _name;}
set{_name = value;}
}
public string Path
{
get{return _path;}
set{_path = value;}
}
public string DefaultDoc
{
get{return _defaultdoc;}
set{_defaultdoc = value;}
}
public string AnonymousUserName
{
get{return _ausername;}
set{_ausername = value;}
}
public string AnonymousUserPass
{
get{return _auserpass;}
set{_auserpass = value;}
}
}
<summary>
Collection Virtualdirectories
</summary>

public class VirtualDirectories:System.Collections.Hashtable
{
Public Virtualdirectories ()
{
}
Add a new method
Public VirtualDirectory Find (string strName)
{
Return (VirtualDirectory) this[strname];
}
}
}





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.