How to Use C# Add Website and Virtual Directory?

How to Use C# Add Website and Virtual Directory? This post shares how to use C# to add websites, application pools, and virtual directories to realize website management. As a developer who develops web projects in C# language, he is basically familiar with some IIS management tasks, such as manually creating a website on IIS, Create applications, create virtual directories, etc., so have you ever thought about implementing a website management tool by yourself to realize automatic website creation? This article explains how to implement such a website management tool.

How to Use C# Add Website and Virtual Directory?
How to Use C# Add Website and Virtual Directory?

Generally speaking, website management tools can complete some tasks that can be used to create websites on Windows servers without IIS, create application pools, bind domain names, establish virtual directories, applications, etc., as well as database-related management tasks. Such tools are convenient Novice user management websites, you can find that some service providers that provide windows vps or windows cloud servers will also provide such website management tools on the windows vps or windows cloud server you purchased.

The following will introduce how to use C# code to add functions such as IIS application pool, website, virtual directory, application, etc., and associate the added application pool with the website. But before we start, let’s show the interface of this sample program:

image 7
How to Use C# Add Website and Virtual Directory?

Package installer download

In the source code, I packaged the program as an installer. You can download and experience the packaged program. Also note that whether you clone the source code from GitHub or download the installer to experience it, you need to Use administrator permissions to run the program or run VS2019 to open the source code, otherwise it will report an error of no permission. After all, operating IIS requires administrator permissions.

download address: click here to download

Tips: Click a few more times when downloading, because free members will see advertisements.

How to Use C# Add Website Youtube

How to Use C# Add Website and Virtual Directory?

C# add application pool

image 8
How to Use C# Add Website and Virtual Directory?
ServerManager serverManager = new ServerManager();
if (textBox4.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the application pool name");
    return;
}
if (comboBox2.SelectedItem == null)
{
    MessageBox.Show("Please select Manage Pipeline mode");
    return;
}
if (comboBox1.SelectedItem == null)
{
    MessageBox.Show("Please select Identity type");
    return;
}
var appool = serverManager.ApplicationPools.Add(textBox4.Text);
appool.ManagedPipelineMode = (ManagedPipelineMode)Enum.Parse(typeof(ManagedPipelineMode), omboBox2.SelectedItem.ToString());
appool.ProcessModel.IdentityType = (ProcessModelIdentityType)Enum.Parse(typeof(ProcessModelIdentityType), omboBox1.SelectedItem.ToString());
serverManager.CommitChanges();

MessageBox.Show("Application pool created successfully");

How to Use C# Add Website and Virtual Directory?

Just like the code above, a ServerManager object is instantiated at the beginning. This object is very important. When we add websites, virtual directories, application pools, and applications through C#, we will always use it. You need to pass Nuget Add a reference to the namespace Microsoft.Web.Administration.

After adding the application pool, you can see the result as shown in the figure below in IIS:

image 10
How to Use C# Add Website and Virtual Directory?

C# Add website

image 9
How to Use C# Add Website and Virtual Directory?
if (textBox1.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the website name");
    return;
}
if (textBox6.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please specify the website path");
    return;
}
if (textBox8.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please create an application pool first");
    return;
}
try
{
    ServerManager serverManager = new ServerManager();
    Site site = serverManager.Sites.Add(textBox1.Text.Trim(), textBox6.Text, int.Parse(textBox13.Text));
    site.ServerAutoStart = true;
    site.Applications[0].ApplicationPoolName = textBox8.Text;

    site.Bindings.Clear();
    site.Bindings.Add($"{textBox5.Text}:{textBox13.Text}:{textBox2.Text}", "http"); //ip: port: domain name

    serverManager.CommitChanges();

    site.Start();
    MessageBox.Show("Successful website creation!");
}
catch (Exception ex)
{
    MessageBox.Show($"There was an error in the process of creating a website, the reason: {ex.Message}");
}

How to Use C# Add Website and Virtual Directory?

The most important code is the website creation code in the try-catch block. You can see that the ServerManager object is still used to complete the website creation work. While creating the website, the code is set to start automatically, that is, after the website is created Start the website, then set up the application pool for the website, and finally submit the changes by calling the serverManager.CommitChanges method, which completes the creation of the website.

After adding the website, refresh the IIS to see the website you just added successfully, as shown in the figure below, you can see that the domain name, port, etc. have been successfully bound.

View the website added by C# on IIS
View the website added by C# on IIS

Next, look at how to implement the function of adding a virtual directory through C# code.


C# add virtual directory

C# add virtual directory
C# add virtual directory
if (textBox3.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the name of the virtual directory");
    return;
}
if (textBox7.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the virtual directory path");
    return;
}
if (!Directory.Exists(textBox7.Text))
{
    MessageBox.Show("Don't enter randomly, the virtual directory must exist!");
    return;
}
try
{
    ServerManager serverManager = new ServerManager();
    var app = serverManager.Sites[comboBox4.SelectedText].Applications[0];
    app.VirtualDirectories.Add($"/{textBox3.Text}", textBox7.Text);

    serverManager.CommitChanges();

    MessageBox.Show("The virtual directory was created successfully!");
}
catch (Exception ex)
{
    MessageBox.Show($"Error creating virtual directory, reason: {ex.Message}");
}

How to Use C# Add Website and Virtual Directory?

The above code also completes the addition of the virtual directory through the ServerManager object. It should be noted here that adding a virtual directory requires the use of the / symbol to set the path. I did not specify the / symbol at the beginning, and the result was an error, and the addition was correct.

Virtual Directory Nested Application

In the process of actually deploying a website on IIS, you can nest applications in virtual directories, or nest applications in applications, just like Russian dolls, one by one is all right.

The following sample code is to add an application in the virtual directory.

if (string.IsNullOrEmpty(comboBox4.SelectedText))
{
    MessageBox.Show("Please choose the affiliated website, if there is no option, please add a website first!");
    return;
}
if (textBox3.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the name of the virtual directory!");
    return;
}
if (textBox14.Text.IsNullOrWhiteSpace())
{
    MessageBox.Show("Please enter the application name!");
    return;
}
if (!Directory.Exists(textBox15.Text))
{
    MessageBox.Show("Don't input randomly, the application directory must exist!");
    return;
}

try
{
    ServerManager serverManager = new ServerManager();
    var site = serverManager.Sites[comboBox4.SelectedText];
    var app = site.Applications.Add($"/{textBox3.Text}/{textBox14.Text}", textBox15.Text);
    app.ApplicationPoolName = textBox4.Text; //Set the application pool
    serverManager.CommitChanges();

    MessageBox.Show("The application pool is successfully created in the virtual directory!");
}
catch (Exception ex)
{
    MessageBox.Show($"Error creating application pool in virtual directory, reason: {ex.Message}");
}

How to Use C# Add Website and Virtual Directory?

To add an application to the virtual directory, you only need to use the line of code site.Applications.Add($”/{textBox3.Text}/{textBox14.Text}”, textBox15.Text); in the above try-catch block, textBox3 .Text is the name of the virtual directory and textBox14.Text is the name of the application. After adding it as shown in the figure below:

Use C# to add applications in the specified virtual directory
Use C# to add applications in the specified virtual directory
Use C# to add applications under the virtual directory
Use C# to add applications under the virtual directory

C# add application

C# code to add applications under the selected website
C# code to add applications under the selected website
if (string.IsNullOrEmpty(comboBox5.SelectedText))
{
    MessageBox.Show("Please choose the affiliated website, if there is no option, please add a website first!");
    return;
}
try
{
    ServerManager serverManager = new ServerManager();
    var site = serverManager.Sites[comboBox5.SelectedText];
    var app = site.Applications.Add($"/{textBox12.Text}", textBox11.Text);
    app.ApplicationPoolName = textBox4.Text; //Set the application pool
    serverManager.CommitChanges();

    MessageBox.Show("The application pool was successfully created under the site root directory!");
}
catch (Exception ex)
{
    MessageBox.Show($"Error creating application pool in site root directory, reason: {ex.Message}");
}

How to Use C# Add Website and Virtual Directory?

View the application just added in IIS
How to Use C# Add Website and Virtual Directory? View the application just added in IIS

Github: https://github.com/jhrscom/sitemanage

Conclusion

The above code is the most recent work, in writing a Windows service program that automatically recycles the IIS application pool and a demo program of the website management tool written by hand. The above code is just the most basic to complete adding a website and adding a virtual directory on IIS. Applications, application pools, etc.; in fact, you can add a website through C# code, C# add application pool, C# code to add virtual directories to the website, C# code to add applications to the website, and other functions to implement a website management tool of your own.

The purpose of writing this program is to realize automatic site migration and deployment between two Windows servers or multiple Windows servers in an intranet environment and to automatically create a website on the target server. The operation and maintenance personnel only need to fill in the IP address of the new server, domain name, certificate setting, and so on. The rest of the work will be automatically migrated from the old server to the new server by the program to complete the website. Moving deployment.

Leave a Comment