開發一個 WinForm 安裝程式,功能包含:
使用 Microsoft.Web.Administration (nuget: Microsoft.Web.Administration) 操作 IIS 設定存儲 (applicationHost.config)。
using Microsoft.Web.Administration;
public void CreateIisSite(string siteName, string physicalPath, string appPoolName, int port) {
using (ServerManager sm = new ServerManager()) {
// 1. 應用程式池
if (sm.ApplicationPools[appPoolName] == null) {
var pool = sm.ApplicationPools.Add(appPoolName);
pool.ManagedRuntimeVersion = "v4.0";
pool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
sm.CommitChanges();
}
// 2. 網站
if (sm.Sites[siteName] == null) {
var site = sm.Sites.Add(siteName, "http", $"* :{port}:", physicalPath);
site.ApplicationDefaults.ApplicationPoolName = appPoolName;
// 權限:給 IIS_IUSRS 讀取權限
setFolderPermissions(physicalPath, "IIS_IUSRS", FileSystemRights.ReadAndExecute);
sm.CommitChanges();
}
}
}
public void RemoveIisSite(string siteName, string appPoolName) {
using (ServerManager sm = new ServerManager()) {
var site = sm.Sites[siteName];
if (site != null) {
sm.Sites.Remove(site);
sm.CommitChanges();
}
var pool = sm.ApplicationPools[appPoolName];
if (pool != null && pool.Applications.Count == 0) { // 僅無其他應用時刪除
sm.ApplicationPools.Remove(pool);
sm.CommitChanges();
}
}
}
直接執行 DROP DATABASE [DbName],需確保無活動連線:
public void DropDatabase(string connStr, string dbName) {
using (var conn = new SqlConnection(connStr)) {
conn.Open();
// 1. 設定單用戶模式強制斷開連線
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = $@"
ALTER DATABASE [{dbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [{dbName}];";
cmd.ExecuteNonQuery();
}
}
}
public void DeleteInstallFolder(string path) {
if (Directory.Exists(path)) {
// 避免檔案被佔用,先嘗試釋放
Directory.Delete(path, true); // 遞歸刪除
}
}
requireAdministrator)。%windir%\\system32\\inetsrv\\Microsoft.Web.Administration.dll 或 NuGet 安裝。