1. 程式人生 > 實用技巧 >C#打包--如何用VS2005製作Web安裝程式(下)

C#打包--如何用VS2005製作Web安裝程式(下)

C#打包--如何用VS2005製作Web安裝程式(下)

#region WriteRegistryKey 寫登錄檔。安裝部署中,直接有一個登錄檔編輯器,可以在那裡面設定。

        private void WriteRegistryKey()

        {

            // 寫登錄檔

            RegistryKey hklm = Registry.LocalMachine;

            RegistryKey cqfeng = hklm.OpenSubKey("SOFTWARE", true);

            RegistryKey F 
= cqfeng.CreateSubKey("cqfeng"); F.SetValue("FilePath", "kkkk"); } #endregion

操作IIS,建立網站等。可參考: 用VS2005製作網頁對IIS進行操作
#region Connect 連線IIS伺服器

        public bool Connect()

        {

            if (iis == null)

                return false;

            try

            {

                _iisServer 
= new DirectoryEntry("IIS://" + iis + "/W3SVC/1"); _target = iis; _connection = new ConnectionOptions(); _scope = new ManagementScope(@"\" + iis + @"\root\MicrosoftIISV2", _connection); _scope.Connect(); } catch
{ return false; } return IsConnected(); } public bool IsConnected() { if (_target == null || _connection == null || _scope == null) return false; return _scope.IsConnected; } #endregion #region IsWebSiteExists 判斷網站是否已經存在 public bool IsWebSiteExists(string serverID) { try { string siteName = "W3SVC/" + serverID; ManagementObjectSearcher searcher = new ManagementObjectSearcher(_scope, new ObjectQuery("SELECT * FROM IIsWebServer"), null); ManagementObjectCollection webSites = searcher.Get(); foreach (ManagementObject webSite in webSites) { if ((string)webSite.Properties["Name"].Value == siteName) return true; } return false; } catch { return false; } } #endregion #region GetNextOpenID 獲得一個新的ServerID private int GetNextOpenID() { DirectoryEntry iisComputer = new DirectoryEntry("IIS://localhost/w3svc"); int nextID = 0; foreach (DirectoryEntry iisWebServer in iisComputer.Children) { string sname = iisWebServer.Name; try { int name = int.Parse(sname); if (name > nextID) { nextID = name; } } catch { } } return ++nextID; } #endregion #region CreateWebsite 新增網站 public string CreateWebSite(string serverID, string serverComment, string defaultVrootPath, string HostName, string IP, string Port) { try { ManagementObject oW3SVC = new ManagementObject(_scope, new ManagementPath(@"IIsWebService='W3SVC'"), null); if (IsWebSiteExists(serverID)) { return "Site Already Exists..."; } ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters("CreateNewSite"); ManagementBaseObject[] serverBinding = new ManagementBaseObject[1]; serverBinding[0] = CreateServerBinding(HostName, IP, Port); inputParameters["ServerComment"] = serverComment; inputParameters["ServerBindings"] = serverBinding; inputParameters["PathOfRootVirtualDir"] = defaultVrootPath; inputParameters["ServerId"] = serverID; ManagementBaseObject outParameter = null; outParameter = oW3SVC.InvokeMethod("CreateNewSite", inputParameters, null); // 啟動網站 string serverName = "W3SVC/" + serverID; ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null); webSite.InvokeMethod("Start", null); return (string)outParameter.Properties["ReturnValue"].Value; } catch (Exception ex) { return ex.Message; } } public ManagementObject CreateServerBinding(string HostName, string IP, string Port) { try { ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath("ServerBinding"), null); ManagementObject serverBinding = classBinding.CreateInstance(); serverBinding.Properties["Hostname"].Value = HostName; serverBinding.Properties["IP"].Value = IP; serverBinding.Properties["Port"].Value = Port; serverBinding.Put(); return serverBinding; } catch { return null; } } #endregion

好了,準備工作已經做完,現在開始寫最重要的Install方法了 整個方法寫完後如下:
#region Install 安裝

        ///

        /// 安裝資料庫

        ///

        ///

        public override void Install(IDictionary stateSaver)

        {

            

base.Install(stateSaver);

            dir = this.Context.Parameters["dir"];

            DBName = this.Context.Parameters["DBNAME"].ToString();

            ServerName = this.Context.Parameters["server"].ToString();

            AdminName = this.Context.Parameters["user"].ToString();

            AdminPwd = this.Context.Parameters["pwd"].ToString();

            iis = this.Context.Parameters["iis"].ToString(); ;

            port = this.Context.Parameters["port"].ToString();

           

            //寫入獲取的安裝程式中的變數,此段程式碼為除錯用可以不新增

            this.sqlConn.ConnectionString = "Packet size=4096;User ID=" + AdminName + ";Data Source=" + ServerName + ";Password=" + AdminPwd + ";Persist Security Info=False;Integrated Security=false";

            // 執行SQL 安裝資料庫 可選擇時恢復或者時直接建立

            if(!CreateDBAndTable(DBName))

            {

                throw new ApplicationException("建立資料庫時出現嚴重錯誤!");

            }

           

            // 從備份資料庫檔案恢復資料庫

            

            // 新增網站

            Connect();

            //string serverID = GetNextOpenID().ToString();

            //string serverComment = websitenName;

                     // 下面的資訊為測試,可以自己編寫文字框來接收使用者輸入資訊

            string serverID = "5555";

            string serverComment = "cqfeng";

            string defaultVrootPath = this.Context.Parameters["targetdir"];

            if (defaultVrootPath.EndsWith(@""))

            {

                defaultVrootPath = defaultVrootPath.Substring(0, defaultVrootPath.Length-1);

            }

            string HostName = "";

            string IP = "";

            string Port = port;

            string sReturn = CreateWebSite(serverID, serverComment, defaultVrootPath, HostName, IP, Port);

           

            // 修改web.config

            if (!WriteWebConfig())

            {

                throw new ApplicationException("設定資料庫連線字串時出現錯誤");

            }

            // 寫登錄檔

            WriteRegistryKey();

        }

        #endregion

刪除時的方法。在本文中未詳細操作,比如刪除站點,刪除資料庫等。如果需要,請你自己補足
#region Uninstall 刪除

        public override void Uninstall(IDictionary savedState)

        {

            if (savedState == null)

            {

                throw new ApplicationException("未能解除安裝!");

            }

            else

            {

                base.Uninstall(savedState);

            }

}

        #endregion

編譯,然後選擇安裝,如圖:

第一圖:

第二圖:

第三圖:

抱歉,我不知道在這裡怎麼使登入密碼框輸入時顯示為*號 第四圖:

第五圖:

安裝:

安裝完成:

安裝後的IIS

安裝目錄:

安裝後的資料庫:

至此,一個簡單的部署web程式的exe檔案已經完成,當然,省略了很多東西,比如,對安裝機器的判斷(IIS版本,Framework版本,SQL Server版本等),IIS站點屬性等設定(預設頁面,訪問許可權,執行許可權等),解除安裝程式時應該刪除的東西等等。這些東西,在MSDN裡面可以查詢到相關說明,如果你需要,只有辛苦一下了,嘿嘿。 相信有了這些,自己用WinForm來寫安裝程式也時可以了哈。