我需要以编程方式创建一个IIS网站。任何人都可以告诉我这样做的代码吗?
答案 0 :(得分:4)
如果针对IIS 7或更高版本,请尽量不要使用WMI(DirectoryEntry
)。 Microsoft.Web.Administration.dll
(windows\system32\inetsrv
)中有一个名为ServerManager
的API,可以让它变得非常简单:
ServerManager serverManager = new ServerManager();
serverManager.Sites.Add("Mysite", "c:\temp\", 8080);
答案 1 :(得分:2)
这适用于IIS 6.0及更高版本,它是用VB.Net编写的(如果需要的话,它足够小,可以很容易地转换为C#)。我也没有写这个,我在这里找到它(我确实编译了它以确保它会构建):http://www.gafvert.info/notes/VBNET-Create-Website-IIS6.htm
Imports System.DirectoryServices
Imports System
Public Class IISAdmin
Public Shared Function CreateWebsite(webserver As String, serverComment As String, serverBindings As String, homeDirectory As String) As Integer
Dim w3svc As DirectoryEntry
w3svc = New DirectoryEntry("IIS://localhost/w3svc")
'Create a website object array
Dim newsite() As Object
newsite = New Object(){serverComment, new Object(){serverBindings}, homeDirectory}
'invoke IIsWebService.CreateNewSite
Dim websiteId As Object
websiteId = w3svc.Invoke("CreateNewSite", newsite)
Return websiteId
End Function
Public Shared Sub Main(args As String())
Dim a As Integer
a = CreateWebsite("localhost", "Testing.com", ":80:Testing.com", "C:\\inetpub\\wwwroot")
Console.WriteLine("Created website with ID: " & a)
End Sub
End Class
public static int CreateWebsite(string webserver, string serverComment, string serverBindings, string homeDirectory)
{
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");
//Create a website object array
object[] newsite = new object[]{serverComment, new object[]{serverBindings}, homeDirectory};
//invoke IIsWebService.CreateNewSite
object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite);
return (int)websiteId;
}