How to enumerate all web sites with c#
23.05.2007
The c# source code below is for a very simple console application that will display a simple list of the web sites on the local computer.
It uses the System.DirectoryServices assembly to provide access to the IIS Metabase. This must be specifically added to the References section of your Visual Studio.NET project (if you are using Visual Studio.NET ).
using
System;
using
System.DirectoryServices;
namespace
EnumSites
{
///
/// Sample application to show enumeration of IIS web sites.
///
class Class1
{
///
/// Enumerate all WebSites on the
server
///
[STAThread]
static void
Main(string[]
args)
{
try
{
const string WebServerSchema = "IIsWebServer";
// Case Sensitive
string ServerName = "LocalHost";
DirectoryEntry W3SVC =
new DirectoryEntry("IIS://" +
ServerName + "/w3svc", "Domain/UserCode", "Password");
foreach (DirectoryEntry Site
in
W3SVC.Children)
{
if (Site.SchemaClassName ==
WebServerSchema)
Console.WriteLine(Site.Name + " - " +
Site.Properties["ServerComment"].Value.ToString());
}
}
// Catch any errors
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
}
}
}
To compile the source code above you will need to have the .NET Framework installed. You then need to simply call CSC.EXE which is the c# compiler with the name of the source file. Copy and paste the above code into Notepad and then save it to your hard drive as enumsites.cs
On my machine the CSC.EXE file was location in D:\Winnt\Microsoft.NET\Framework\V1.0.3705\
By following the screen snap below you can see the actions that were taken.
- Compiling the enumsites.cs source code
- Verified that enumsites.exe was created - 4096 bytes
- Run the enumsites.exe application which then displayed the Web Sites on the local computer.
Related information
