WEB程序打包详解:(连接SQL2005数据库,修改配置文件,建立虚拟目录)
生活随笔
收集整理的這篇文章主要介紹了
WEB程序打包详解:(连接SQL2005数据库,修改配置文件,建立虚拟目录)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
做了一個web的打包程序,和大家分享一下。
第一步:新建——文件——項目,彈出對話框
?
如圖,選擇安裝和部署——安裝項目 這里要解釋一下了,一般來說,制作web安裝程序選擇web安裝項目,而我沒有選擇web安裝項目的原因是web安裝項目制作出來的安裝包是不可以選擇軟件的安裝路徑的,而安裝項目制作出來的安裝包是可以選擇軟件的安裝目錄的。 第二步:右鍵解決方案中的安裝項目——視圖——文件系統 ?如圖 彈出 這樣的文件系統界面,將你發布完的文件復制到應用程序文件夾下 第三步:右鍵解決方案中的安裝項目——視圖——用戶界面(和第二步一樣,不截圖了)彈出下圖 其中客戶信息根據項目需求可有可無,文本框(A)文本框(B)要是配置數據庫連接和虛擬路徑的朋友們還是要加的,移動到安裝文件夾之上。 第四步:右鍵文本框(A)——屬性窗口,如圖 ? 解釋一下,Edit1Property和Edit2Property是自定義的,朋友們可以隨便寫,但是要有意義并且能記住,等會兒會用的。 第五步:右鍵文本框(B)——屬性窗口,如圖 ?在解釋,Edit1Property,Edit2Property,Edit3Property,Edit4Property均同上,唯一解釋的是Edit2Value中填寫的值是默認值,朋友們根據個人情況選填。 第六步:右鍵解決方案——添加——新建項目——類庫,刪除Class1.CS文件。在這個類庫上右鍵——添加——新建項 如圖,選擇安裝程序類 第七步:右鍵解決方案中的安裝項目——添加——項目輸出,如下圖 下拉框中就是你剛才建的類庫名稱,選擇主輸出——確定。 第八步:右鍵解決方案中的安裝項目——視圖——自定義操作,如下圖 右鍵安裝——添加自定義操作,選擇應用程序文件夾下面的主輸出——確定。 這時在安裝文件夾下面就多了一個主輸出,點擊一下,屬性如下圖 圖片可能看不清楚,主要只改一個屬性,CustomActionData 這個值很重要 /dbname=[DBNAME] /password=[PASSWORD] /user=[USERNAME]? /server=[DBSERVERNAME] /iis=[IISSERVER] /port=[PORT] /targetdir="[TARGETDIR]/" 這么重要就解釋一下,小寫的字母全是你建的那個安裝程序類中要用到的字段,這個屬性主要就是傳值用的,將安裝信息通過這個屬性傳入給安裝程序類,大寫的字母就是當時文本框(A)文本框(B)中你自定義的那些值,targetdir是獲得軟件的安裝目錄用的。 到這里,基本上就沒有安裝項目什么事了,接下來重點在安裝程序類。首先:準備工作,我所用到的引用 以下是這個類的所有代碼 using System;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Configuration.Install;
using System.Management;
using System.Collections;
using Microsoft.Win32;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using IWshRuntimeLibrary;
using System.Windows.Forms;
using System.Diagnostics; ?
namespace ***ClassLibrary
{
??? [RunInstaller(true)]
??? public partial class ***Installer : Installer
??? {
??????? public ***Installer()
??????? {
??????????? InitializeComponent();
??????? } ??????? #region 變量
??????? private string server = string.Empty;
??????? private string dbname = string.Empty;
??????? private string user = string.Empty;
??????? private string password = string.Empty;
??????? private string dir = string.Empty;
??????? private string iis = string.Empty;
??????? private string port = string.Empty;
??????? #endregion
??????? #region?創建快捷方式(這個WEB快捷方式的創建方法,就是在桌面上創建了一個url的文件)
??????? private void CreateKJFS()
??????? {
??????????? StreamWriter sw = new StreamWriter(System.IO.File.Open(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "", FileMode.Create, FileAccess.Write));
??????????? sw.WriteLine("[InternetShortcut]");
??????????? sw.WriteLine("URL=http://"+iis+"/" + port);
??????????? sw.WriteLine("IconFile=" + dir.Substring(0, dir.LastIndexOf("//")) + "");
??????????? sw.WriteLine("IconIndex=0");
??????????? sw.Flush();
??????????? sw.Close();
??????? }
??????? #endregion
??????? #region 移動數據庫(解釋,為什么要移動數據庫呢?主要是我的數據庫文件是和發布文件一起放入了應用程序文件夾中,這樣在卸載的時候就會默認卸載掉我的數據庫,后果十分嚴重,所以,我在安裝目錄下創建了一個文件夾Data,根據條件移動文件,由于是代碼自動創建的文件夾,所以卸載時就不會被卸載掉了)
??????? private void MoveData()
??????? {
??????????? if (!Directory.Exists(dir + ""))?//如果不存在Data文件夾
??????????? {
??????????????? Directory.CreateDirectory(dir + "");?//創建Data文件夾
??????????????? Directory.Move(dir + "", dir + "");?//移動文件
??????????????? Directory.Move(dir + "", dir + "");?//同上
??????????????? AddDB();//附加數據庫(方法在下面)
??????????? }
??????????? else?//如果存在Data文件夾
??????????? {
??????????????? if (System.IO.File.Exists(dir + "") && System.IO.File.Exists(dir + "")) //并且存在數據庫文件
??????????????? {
??????????????????? LeaveDB(); //分離數據庫
??????????????????? DialogResult r1 = MessageBox.Show("您確定要用原始數據替換您的現有數據嗎?替換前建議您先備份好現有數據,一旦替換,數據將無法恢復!","注意", MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
??????????????????? int ss1 = (int)r1;
??????????????????? if (ss1 == 6)?//如果確定替換
??????????????????? {
??????????????????????? System.IO.File.Delete(dir + ""); //刪除文件
??????????????????????? System.IO.File.Delete(dir + ""); //同上
??????????????????????? Directory.Move(dir + "", dir + "");?//移動文件
??????????????????????? Directory.Move(dir + "", dir + ""); //同上
??????????????????????? AddDB(); //附加數據庫
??????????????????? }
??????????????????? else
??????????????????? {
??????????????????????? AddDB(); //附加數據庫
??????????????????? }
??????????????? }
??????????????? else?//存在文件夾但是不存在文件
??????????????? {
??????????????????? Directory.Move(dir + "", dir + "");
??????????????????? Directory.Move(dir + "", dir + "");
??????????????????? AddDB();
??????????????? }
??????????? }
??????? }
??????? #endregion
??????? #region 附加數據庫
??????? private void AddDB()
??????? { ??????????? string connStr = string.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096", server, user, password); ??????????? string strSql = "if not exists (select * From master.dbo.sysdatabases where name='" + dbname + "') begin EXEC sp_attach_db? @dbname? =? N'" + dbname + "'," + "@filename1? =? N'" + dir + "," + "@filename2? =? N'" + dir + " end";
??????????? ExecuteSql(connStr, "master", strSql);
??????? }
??????? #endregion
??????? #region 分離數據庫
??????? private void LeaveDB()
??????? {
??????????? string connStr = string.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096", server, user, password);
??????????? string strSql = "EXEC sp_detach_db '數據庫名稱', 'true' ";
??????????? ExecuteSql(connStr, "master", strSql);
??????? }
??????? #endregion
?
?
?
??????? #region 創建虛擬目錄(這段是網上copy的,不是自己做的不敢解釋)
??????? private void CreateVirtualDir()
??????? {
??????????? try
??????????? {
??????????????? string constIISWebSiteRoot = "IIS://" + iis + "/W3SVC/1/ROOT";
??????????????? DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);
??????????????? DirectoryEntry newRoot = root.Children.Add(port, root.SchemaClassName);
??????????????? newRoot.Properties["Path"][0] = dir;
??????????????? newRoot.Properties["AppIsolated"][0] = 2;???????????? // 值 0 表示應用程序在進程內運行,值 1 表示進程外,值 2 表示進程池
??????????????? newRoot.Properties["AccessScript"][0] = true;????????? // 可執行腳本
??????????????? newRoot.Invoke("AppCreate", true);
??????????????? newRoot.Properties["DefaultDoc"][0] = "Default.aspx";//設置起始頁
??????????????? newRoot.Properties["AppFriendlyName"][0] = port;?? // 應用程序名
??????????????? newRoot.CommitChanges();
??????????????? root.CommitChanges(); ??????????????? string fileName = Environment.GetEnvironmentVariable("windir") + @"/Microsoft.NET/Framework/v2.0.50727/aspnet_regiis.exe";
??????????????? ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
??????????????? //處理目錄路徑
??????????????? string path = newRoot.Path.ToUpper();
??????????????? int index = path.IndexOf("W3SVC");
??????????????? path = path.Remove(0, index);
??????????????? //啟動aspnet_iis.exe程序,刷新教本映射
??????????????? startInfo.Arguments = "-s " + path;
??????????????? startInfo.WindowStyle = ProcessWindowStyle.Hidden;
??????????????? startInfo.UseShellExecute = false;
??????????????? startInfo.CreateNoWindow = true;
??????????????? startInfo.RedirectStandardOutput = true;
??????????????? startInfo.RedirectStandardError = true;
??????????????? Process process = new Process();
??????????????? process.StartInfo = startInfo;
??????????????? process.Start();
??????????????? process.WaitForExit();
??????????????? string errors = process.StandardError.ReadToEnd();
??????????????? if (errors != string.Empty)
??????????????????? throw new Exception(errors);
??????????? }
??????????? catch (Exception ee)
??????????? {
??????????????? MessageBox.Show("虛擬目錄創建失敗!您可以手動創建! " + ee.Message, "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
??????????? } ??????? }
??????? #endregion
??????? #region 修改web.config的連接數據庫的字符串
??????? private void?WriteWebConfig()
??????? {
??????????? System.IO.FileInfo FileInfo = new System.IO.FileInfo(dir + "/web.config");
??????????? if (!FileInfo.Exists)?//不存在web.config文件
??????????? {
??????????????? throw new InstallException("沒有找到web.config配置文件!");
??????????? }
??????????? System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
??????????? xmlDocument.Load(FileInfo.FullName); ??????????? bool FoundIt = false;
??????????? foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["connectionStrings"])
??????????? {
??????????????? if (Node.Name == "add")
??????????????? {
??????????????????? if (Node.Attributes.GetNamedItem("name").Value == "配置文件中name的值")
??????????????????? {
??????????????????????? Node.Attributes.GetNamedItem("connectionString").Value = String.Format("Persist Security Info=False;Data Source={0};database={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1", server, dbname, user, password); ????????????????????FoundIt = true;
??????????????????? }?? ??????????????? }
??????????? }
??????????? if (!FoundIt)
??????????? {
??????????????? throw new InstallException("修改web.config配置文件失敗!");
??????????? }
??????????? xmlDocument.Save(FileInfo.FullName);
??????? }
??????? #endregion
??????? #region 執行SQL語句所用方法
??????? private void ExecuteSql(string connStr, string DatabaseName, string Sql)
??????? {
??????????? SqlConnection conn = new SqlConnection(connStr);
??????????? SqlCommand cmd = new SqlCommand(Sql, conn); ??????????? conn.Open();
??????????? conn.ChangeDatabase(DatabaseName);
??????????? try
??????????? {
??????????????? cmd.ExecuteNonQuery();
??????????? }
??????????? finally
??????????? {
??????????????? conn.Close();
??????????? }
??????? }
??????? #endregion ?
?#region Install 安裝(安裝主方法)
??????? public override void Install(IDictionary stateSaver)
??????? {
??????????? base.Install(stateSaver);
??????????? dir = this.Context.Parameters["targetdir"].ToString();
??????????? server = this.Context.Parameters["server"].ToString();
??????????? dbname = this.Context.Parameters["dbname"].ToString();
??????????? user = this.Context.Parameters["user"].ToString();
??????????? password = this.Context.Parameters["password"].ToString();
??????????? iis = this.Context.Parameters["iis"].ToString();
??????????? port = this.Context.Parameters["port"].ToString();
??????????? //移動數據庫
??????????? MoveData();
??????????? //創建虛擬目錄
??????????? CreateVirtualDir();
??????????? //重寫Config
??????????? WriteWebConfig();
??????????? //創建快捷方式
??????????? CreateKJFS();
??????? }
??????? #endregion
??? }
}
轉載于:https://www.cnblogs.com/wujy/archive/2012/01/31/2333053.html
總結
以上是生活随笔為你收集整理的WEB程序打包详解:(连接SQL2005数据库,修改配置文件,建立虚拟目录)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#生成XSD规范,利用XmlSchem
- 下一篇: c# 值类型数据与引用类型数据