Monday, June 04, 2007

Create Virtual Directory in IIS using C#

            In my recent project I need to create virtual directory in IIS programmatically.  I was searching on net and found a really good article posted by Dipali Choksi. You can find the artilce here. I have copied that article below for my reference.

 

Using System.DirectoryServices;
private
void btnCreateDirectory_Click(object sender, EventArgs e)
{
          string strSchema = "IIsWebVirtualDir";
          string strRootSubPath = "/W3SVC/1/Root" ;

           // you can specify any server name , "localhost" is for example
           DirectoryEntry deRoot =
                        new DirectoryEntry("IIS://" + "localhost" + strRootSubPath);
         try
        {
                 deRoot.RefreshCache();
                 DirectoryEntry deNewVDir =
                                    deRoot.Children.Add("Name of Virtual Directory", strSchema);

                 deNewVDir.Properties["Path"].Insert(0, "Path for Virtual Directory");
                 deNewVDir.CommitChanges();
                 deRoot.CommitChanges();

                // Create a Application
                if (strSchema == "IIsWebVirtualDir")
                           deNewVDir.Invoke("AppCreate", true);
                // Save Changes
                           deNewVDir.CommitChanges();
                
                deRoot.CommitChanges();
                deNewVDir.Close();
                deRoot.Close();
                lblResult.Text = "Virtual Directory "
                                   + ("Name of Virtual Directory"+ "(" + "Path for Virtual
                                             Directory
" + ") has  been created";
       }
      catch (Exception ex)
     {
                lblResult.Text = ex.Message;
      }
}

Fig (1) Code to create virtual directory using C#

1 comment:

Raja said...

Hi All,
I found a really cool article on same here.
http://www.west-wind.com/WebLog/posts/399.aspx

http://www.15seconds.com/issue/010710.htm

THanks.