How to operate IIS in. net

Source: Internet
Author: User
Tags microsoft iis
Net has actually done a good job for us in this regard. FCL provides a lot of classes to help us complete this task, making our development work very simple and happy. Programming to control IIS is actually very simple, just like ASP ,. in net, you need to use ADSI to operate IIS, but at this time we no longer need GetObject, because. NET provides us with more powerful new features.
System. the directoryservices namespace includes some powerful Dongdong-directoryentry and directoryentries, which provide us with powerful functions to access the Active Directory, these classes allow us to operate IIS, LDAP, NDS, and WinNT with powerful functions :)

However, here we only talk about the control of IIS. In general, operations on IIS are generally performed on virtual directories, so I will refer to this column as the main content.

First of all, we need to figure out the problem of the IIS hierarchy. Below is a picture I have obtained from abroad, which explains the IIS hierarchy well:

[Htmchina: Image id = image1 | 12] [/htmchina: Image]
To understand the control Syntax of IIS, we must understand the hierarchical structure of IIS metadata (metabase. Each node in the figure is called a key, and each key can contain one or more values. These values are what we call properties ), the key in the IIS metadata is consistent with the element in IIS. Therefore, setting the attribute value in the metadata affects the setting in Microsoft IIS. This is the basic idea and core of our programming.

We also need to understand the concept of schema. It indicates the name of the Framework in IIS, that is, it can understand the key type in IIS metadata. Specifically, it refers to the type of each node. We know that IIS has virtual directories, common directories, and files, all of which belong to the IIS elements, and their labels are schema. For example, the schema of the virtual directory is "iisvirtualdir", and the common directory is "iiswebdir ". In this way, when we add or delete directories, IIS will know whether we have added virtual directories or normal directories.

Create virtual directory

Directoryentry is a big gift from. net. We know its function-directory entry. All users who have used ADSI know that when operating IIS and WinNT, we also need to provide their path. When operating IIS, the path format is:

IIS: // computername/service/website/directory

Computername: the name of the server to be operated. It can be either a name or an IP address, and localhost is often used.
Service: the operating server. IIS has web, FTP, and SMTP services. We mainly operate on the web functions of IIS. Therefore, "W3SVC ", for FTP, it should be "msftpsvc"
Website: an IIS service can contain many sites, which are used to set up sites for operations. The value is a number. The default value is 1, indicating the default site. If there are other sites, the number starts from 1 and so on.
Directory: The Directory Name of the operation. The top-level directory of a website is "root", and other directories are its children ).
First, we obtain the top-level directory (root directory) of a Website ):

Directoryentry rootfolder = new directoryentry ("IIS: // localhost/w3svc/1/root ");

If no exception occurs when we create this object, the directory actually exists.

Next we will add a new virtual directory. For example, we want to add "aspcn ":

Directoryentry newvirdir = rootfolder. Children. Add ("aspcn", "iiswebvirtualdir ");
Newvirdir. Invoke ("appcreate", true );
Newvirdir. commitchanges ();
Rootfolder. commitchanges ();

The idea of creating a directory is simple, that is, in the root directory subset (rootfolder. add another record. The add method in the directoryentries class is used here. It returns a directoryentry, indicating the newly added directory. The first parameter is the name of the virtual directory, the second is the schema class name to indicate the directory type we add. Then, use the invoke method of directoryentry to call the "appcreate" method in ADSI to create a directory (it seems that the directory can be created successfully without this step, but for the sake of security, you can call the commitchanges method in the new and root directories to confirm the operation.

When creating a new directory, we can also assign values to the attributes of this directory. However, my practical experience tells me that it is best not to do this. If you assign values when creating a directory, there will be many attributes that cannot be assigned successfully, such as the path attribute that represents the real directory. Therefore, it is recommended that you create a directory first and then assign a value to update the directory information.

Update virtual directory

I believe you are familiar with IIS and understand some important settings in IIS, such as accessread, accesswrite, and accessexecute. You can assign values to the properties attribute set of directoryentry. You can assign values in two ways:

The first method is to call the add method of the properties set, for example:

Dir. properties ["accessread"]. Add (true );

The second is to assign values to the first index:

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

Both methods are feasible. It depends on your preferences.

Before assigning values, we still need to determine the target to assign values. :) here we use the find method of the directoryentries class, for example:

Directoryentry de = rootfolder. Children. Find ("aspcn", "iisvirtualdir ");

After finding it, we can assign values. Make sure you have a good look when assigning values. The virtual directory has a large number of attribute values .. (Too many, I will not repeat the flying knife. You can check it on Microsoft's site :)

Commonly used: accessread, accesswrite, accessexecute, accessscript, defaultdoc, enabledefadoc doc, path

Delete virtual directory

The method to delete a virtual directory is also very simple, that is, to 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 method is to call the delete method of the root directory.

Object [] paras = new object [2];
Paras [0] = "iiswebvirtualdir"; // indicates that a virtual directory is operated.
Paras [1] = "aspcn ";
Rootfolder. Invoke ("delete", paras );
Rootfolder. commitchanges ();

Which one you like depends on programming habits :))

How to operate IIS in. Net (Source code)

Using system;
Using system. Data;
Using system. directoryservices;
Using system. collections;
Namespace aspcn. Management
{
/// <Summary>
/// Summary of iismanager.
/// </Summary>
Public class iismanager
{
// Define
Private string _ server, _ website;
Private virtualdirectories _ virdirs;
Protected system. directoryservices. directoryentry rootfolder;
Private bool _ batchflag;
Public iismanager ()
{
// By default, localhost is used to access the local machine.
_ Server = "localhost ";
_ Website = "1 ";
_ Batchflag = false;
}
Public iismanager (string strserver)
{
_ Server = strserver;
_ Website = "1 ";
_ Batchflag = false;
}
/// <Summary>
/// Define public attributes
/// </Summary>

// Server attribute defines the name of the access machine, which can be IP address and computing name
Public String Server
{
Get {return _ server ;}
Set {_ Server = value ;}
}
// Defines the website attribute as a number. For convenience, use string
// Generally, the first host is 1, the second host is 2, and so on.
Public String website
{
Get {return _ website ;}
Set {_ website = value ;}
}

// Virtual directory name
Public virtualdirectories virdirs
{
Get {return _ virdirs ;}
Set {_ virdirs = value ;}
}
/// <Summary>
/// Define public methods
/// </Summary>

// Connect to the server
Public void connect ()
{
Connecttoserver ();
}
// For convenience of overloading
Public void connect (string strserver)
{
_ Server = strserver;
Connecttoserver ();
}
// For convenience of overloading
Public void connect (string strserver, string strwebsite)
{
_ Server = strserver;
_ Website = strwebsite;
Connecttoserver ();
}
// Determine whether the virtual directory is saved
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 it to the children set of the root user
Directoryentry newvirdir = rootfolder. Children. Add (newdir. Name, "iiswebvirtualdir ";
Newvirdir. Invoke ("appcreate", true );
Newvirdir. commitchanges ();
Rootfolder. commitchanges ();
// 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 .";
}
}
// Obtain 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 is not exists ";
}
Return TMP;
}

// update a virtual directory
Public void Update (virtualdirectory DIR)
{< br> // determine whether the virtual directory to be changed exists
If (_ virdirs. contains (dir. name)
{< br> directoryentry ode = rootfolder. children. find (dir. name, "iiswebvirtualdir";
updatedirinfo (ODE, DIR );
}< br> else
{< br> throw new exception ("this virtual directory is not exists. ";
}< BR >}< br>
// delete a virtual directory
Public void Delete (string strvirdir)
{< br> If (_ virdirs. contains (strvirdir)
{< br> object [] paras = new object [2];
paras [0] = "iiswebvirtualdir "; // indicates that the virtual directory is operated.
paras [1] = strvirdir;
rootfolder. invoke ("delete", paras);
rootfolder. commitchanges ();
}< br> else
{< br> throw new exception ("can't delete" + strvirdir + ", because it isn' t exists. ";
}< BR >}< br> // batch update
Public void updatebatch ()
{< br> batchupdate (_ virdirs );
}< br> // reload a file at: -< br> Public void updatebatch (virtualdirectories VDS)
{< br> batchupdate (VDS );
}< br>
///


// Private method
///

// Connect to the 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 );
}
}
// Execute batch 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 ();
}

// Obtain the virtual directory set
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, _ endefadoc Doc;
Private string _ ausername, _ auserpass, _ name, _ path;
Private int _ flag;
Private string _ defaultdoc;
/// <Summary>
/// Constructor
/// </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; _ endefadoc Doc = false;
_ Flag = 1;
_ Defaultdoc = "default.htm,default.aspx,default.asp,index.htm ";
_ Path = "C :\\";
_ Ausername = ""; _ auserpass = ""; _ name = "";
}
/// <Summary>
/// Define attributes. iisvirtualdir has too many attributes.
/// I only did some important work. Other people need to add their own products.
/// </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 _ endefadoc Doc ;}
Set {_ endefadoc Doc = value ;}
}
Public string name
{
Get {return _ name ;}
Set {_ name = value ;}
}
Public String path
{
Get {return _ path ;}
Set {_ Path = value ;}
}
Public String defaultdoc
{
Get {return _ defadoc Doc ;}
Set {_ defadoc Doc = value ;}
}
Public String anonymoususername
{
Get {return _ ausername ;}
Set {_ ausername = value ;}
}
Public String anonymoususerpass
{
Get {return _ auserpass ;}
Set {_ auserpass = value ;}
}
}
/// <Summary>
/// Set 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.