在部署 ASP.NET Web 應用程式時,若能將 IIS 虛擬目錄建立、資料夾權限設定、資料庫腳本執行等動作整合進單一安裝包,將大幅簡化部署流程。本文將手把手教您使用 Visual Studio 建立專案安裝程式,並透過自訂安裝類別實現 IIS 自動化配置。
在方案中新增一個「類別庫」專案(命名為 InstallClassLibrary),並參考 System.DirectoryServices、System.Configuration.Install 等組件。核心程式碼如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.DirectoryServices;
using System.Diagnostics;
using System.Windows.Forms;
using System.Security.AccessControl;
using System.IO;
namespace InstallClassLibrary
{
[RunInstaller(true)]
public partial class WebInstaller : Installer
{
public WebInstaller()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
CreateVirtualDir();
// 設定資料夾權限給 NETWORK SERVICE
DirectoryInfo di = new DirectoryInfo(@"d:\yourpath\xml");
if ((di.Attributes & FileAttributes.ReadOnly) != 0)
di.Attributes = FileAttributes.Normal;
DirectorySecurity ds = di.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(
"NETWORK SERVICE",
FileSystemRights.Modify,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow));
di.SetAccessControl(ds);
}
void CreateVirtualDir()
{
try
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC/1/root");
DirectoryEntry newRoot = root.Children.Add("virtualName", root.SchemaClassName);
newRoot.Properties["Path"][0] = @"d:\yourpath"; // 可改為 this.Context.Parameters["targetdir"]
newRoot.Properties["AppIsolated"][0] = 2; // 2 = 應用程式集區
newRoot.Properties["AccessScript"][0] = true;
newRoot.Invoke("AppCreate", true);
newRoot.Properties["DefaultDoc"][0] = "login.aspx";
newRoot.Properties["AppFriendlyName"][0] = "applicationName";
newRoot.CommitChanges();
root.CommitChanges();
}
catch (Exception ee)
{
MessageBox.Show(
"虛擬目錄建立失敗!您可以手動建立! " + ee.Message,
"Error",
MessageBoxButtons.AbortRetryIgnore,
MessageBoxIcon.Error);
}
}
}
}
關鍵點說明:
RunInstaller(true) 標記讓安裝程式自動偵測並執行此類別DirectoryEntry 操作 IIS Metabase 建立虛擬目錄AppIsolated = 2 表示使用獨立應用程式集區(建議值)FileSystemAccessRule 給予 NETWORK SERVICE 修改權限,確保 Web 應用程式能讀寫資料夾InstallClassLibrary 輸出在檔案系統編輯器中,右鍵「應用程式資料夾」設定 DefaultLocation 屬性(例如 [ProgramFilesFolder][Manufacturer]\[ProductName])。若需收集更多使用者輸入(如資料庫連線字串),可在「使用者介面」編輯器中新增對話方塊。
Context.Parameters["targetdir"] 取得實際安裝目錄,避免硬編碼IIS:// 提供者Install 方法中加入交易式錯誤處理,失敗時呼叫 Rollback 復原變更透過上述步驟,您即可產出一個功能完整的 .msi 安裝包,一鍵完成 Web 應用程式部署、虛擬目錄建立、權限設定等繁瑣工作,極大提升維運效率。