Programmatically create a web site in IIS using C# and set port number

62,556

Solution 1

If you're using IIS 7, there is a new managed API called Microsoft.Web.Administration

An example from the above blog post:

ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges(); 

If you're using IIS 6 and want to do this, it's more complex unfortunately.

You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).

You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):

string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);

string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;


object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };

object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);

// Returns the Website ID from the Metabase
int id = (int)websiteId;

See more here

Solution 2

Heres the solution.
Blog article : How to add new website in IIS 7

On Button click :

try
 {
  ServerManager serverMgr = new ServerManager();
  string strWebsitename = txtwebsitename.Text; // abc
  string strApplicationPool = "DefaultAppPool";  // set your deafultpool :4.0 in IIS
  string strhostname = txthostname.Text; //abc.com
  string stripaddress = txtipaddress.Text;// ip address
  string bindinginfo = stripaddress + ":80:" + strhostname;

  //check if website name already exists in IIS
    Boolean bWebsite = IsWebsiteExists(strWebsitename);
    if (!bWebsite)
     {
        Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
        mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
        mySite.TraceFailedRequestsLogging.Enabled = true;
        mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
        serverMgr.CommitChanges();
        lblmsg.Text = "New website  " + strWebsitename + " added sucessfully";
     }
     else
     {
        lblmsg.Text = "Name should be unique, " + strWebsitename + "  is already exists. ";
     }
   }
  catch (Exception ae)
  {
      Response.Redirect(ae.Message);
   }

Looping over sites whether name already exists

    public bool IsWebsiteExists(string strWebsitename)
    {
        Boolean flagset = false;
        SiteCollection sitecollection = serverMgr.Sites;
        foreach (Site site in sitecollection)
        {
            if (site.Name == strWebsitename.ToString())
            {
                flagset = true;
                break;
            }
            else
            {
                flagset = false;
            }
        }
        return flagset;
    }

Solution 3

Try the following Code to Know the unUsed PortNo

        DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");

        // Find unused ID PortNo for new web site
        bool found_valid_port_no = false;
        int random_port_no = 1;

        do
        {
            bool regenerate_port_no = false;
            System.Random random_generator = new Random();
            random_port_no = random_generator.Next(9000,15000);

            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {

                    int site_id = Convert.ToInt32(e.Name);
                    //For each detected ID find the port Number 

                     DirectoryEntry vRoot = new DirectoryEntry("IIS://localhost/W3SVC/" + site_id);
                     PropertyValueCollection pvcServerBindings = vRoot.Properties["serverbindings"];
                     String bindings = pvcServerBindings.Value.ToString().Replace(":", "");
                     int port_no = Convert.ToInt32(bindings);

                     if (port_no == random_port_no)
                    {
                        regenerate_port_no = true;
                        break;
                    }
                }
            }

            found_valid_port_no = !regenerate_port_no;
        } while (!found_valid_port_no);

        int newportId = random_port_no;

Solution 4

I have gone though all answer here and also tested. Here is the most clean smarter version of answer for this question. However this still cant work on IIS 6.0. so IIS 8.0 or above is required.

string domainName = "";
string appPoolName = "";
string webFiles = "C:\\Users\\John\\Desktop\\New Folder";
if (IsWebsiteExists(domainName) == false)
{
    ServerManager iisManager = new ServerManager();
    iisManager.Sites.Add(domainName, "http", "*:8080:", webFiles);
    iisManager.ApplicationDefaults.ApplicationPoolName = appPoolName;
    iisManager.CommitChanges();
}
else
{
    Console.WriteLine("Name Exists already"); 
}


public static bool IsWebsiteExists(string strWebsitename)
{
    ServerManager serverMgr = new ServerManager();
    Boolean flagset = false;
    SiteCollection sitecollection = serverMgr.Sites;
    flagset = sitecollection.Any(x => x.Name == strWebsitename);
    return flagset;
}
Share:
62,556
Shiraz Bhaiji
Author by

Shiraz Bhaiji

Architect / dev lead / .net programmer Manager at Evry http://www.evry.no/ Board Member Oslo Software Architecture http://www.meetup.com/Oslo-Software-Architecture/

Updated on July 09, 2022

Comments

  • Shiraz Bhaiji
    Shiraz Bhaiji almost 2 years

    We have been able to create a web site. We did this using the information in this link:

    https://msdn.microsoft.com/en-us/library/ms525598.aspx

    However, we would like to use a port number other that port 80. How do we do this?

    We are using IIS 6

    • kitsune
      kitsune over 14 years
      What IIS version are you using?
    • Wael Dalloul
      Wael Dalloul over 14 years
      you want to specify the port during the setup or you want to add the website to IIS by code?
    • Shiraz Bhaiji
      Shiraz Bhaiji over 14 years
      @Wael Add the web site to IIS and at the same time specify the port number ofthat web site.
    • Majedur
      Majedur over 2 years
      You can check this link. It has full code and instruction. Just make sure your opening visual studio and others in administrator mode. asptricks.net/2016/08/…
  • Shiraz Bhaiji
    Shiraz Bhaiji over 14 years
    Thanks for your reply. But this is how you do it using the UI, I need to know how to do it in code.
  • Shiraz Bhaiji
    Shiraz Bhaiji over 14 years
    Thanks, unfortunatly we are using IIS 6.
  • Dewfy
    Dewfy over 14 years
    Can you use wmi over JScript or VBScript ?
  • kitsune
    kitsune over 14 years
    I did this in a legacy maintenance project once, I'll see whether I can find the code. It's pretty arcane and convoluted unfortunately.
  • kitsune
    kitsune over 14 years
    Great... btw watch out for App Pools... there might be need for some additional configuration...
  • Piotr Kula
    Piotr Kula almost 12 years
    Only for IIS7.. Cannot find reference for IIS6
  • Liakat Hossain
    Liakat Hossain about 5 years
    To check IsWebsiteExists please see my answer. That can be more smarter way
  • batpox
    batpox almost 5 years
    @AdamDrewery Not helpful. Where he works may require it.
  • batpox
    batpox almost 5 years
    @LiakatHossain Although I prefer your lambda style, it is exactly the same logic.