Winform程式安裝後打開出現程式停止執行問題解決方法
我用的是VS2013版本,打包的是Winform應用程式。
一開始以為是打包過程有問題,結果試很多次。每次安裝成功後,一開啟程式,就出現程式停止執行。如下圖所示。
調了一晚上都沒有頭緒,果斷放棄。走進了死衚衕,鑽牛角尖只會是讓自己越來越痛苦,不如休息一下,換換腦子,理理思路。
第二天雖然是週六,但是不甘心,加班找問題。在百度裡面查資料,希望能有一些啟發,果然還是有幫助的。
解決辦法:
1.出現以上問題的主要原因是,主程式中的建立資料庫錯誤,具體一點就是資料庫路徑錯誤。配置檔案app.config中有一處資料庫連線路徑為本機的絕對路徑,後來改成如下
<connectionStrings>
<!-- 資料庫為相對路徑 在根目錄下的App_Data資料夾下-->
<add name="GPSAnalyzer.Properties.Settings.gpsConnectionString"
connectionString="Data Source=|DataDirectory|gps.db" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
2.如下是獲取資料庫路徑程式碼,可以寫在操作資料庫的類中,如***Helper,或者單獨寫在Common類中:
public static string getDBPath()
{
//資料庫絕對路徑
string dbPath = AppDomain.CurrentDomain.BaseDirectory;
if (dbPath.IndexOf("\\bin\\") > 0)
{
if (dbPath.EndsWith("\\bin\\Debug\\"))
dbPath = dbPath.Replace("\\bin\\Debug", "");
if (dbPath.EndsWith("\\bin\\Release\\"))
dbPath = dbPath.Replace("\\bin\\Release", "");
}
if (!dbPath.EndsWith("App_Data\\"))
dbPath = dbPath + "App_Data\\";
AppDomain.CurrentDomain.SetData("DataDirectory", dbPath);
string sqliteConn_temp = ConfigurationManager.AppSettings["sqliteConn"];
string[] temp = sqliteConn_temp.Split('|');
string db_filename = temp[2].Split(';')[0];
dbPath = dbPath + db_filename;
return dbPath;
}
3.為什麼能發現這個問題,是因為後來在程式中增加了錯誤日誌。這個很重要!!!!!!方便除錯!!!!!
由於沒想到程式在一執行時就出Bug了,所以在主程式中並沒有捕獲異常,寫錯誤日誌,這是最大的失誤。為了找出以上問題,我在主程式中增加了以下捕獲異常的程式碼:
static void Main()
{
#region 異常 程式停止執行
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);// UnhandledException事件來處理非 UI 執行緒異常
//新增非UI上的異常.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
#endregion
//以下是建立資料庫、程式入口等程式碼
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
Utility.Log.WriteSysLog("Program," + MethodBase.GetCurrentMethod().Name +" 錯誤:"+ ex.Message + "\n\nStack Trace:\n" + ex.StackTrace, ex);
}
catch (Exception exc)
{
try
{
MessageBox.Show(" Error",
" Could not write the error to the log. Reason: "
+ exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
}
再次執行安裝好的程式,程式依然停止執行。不過沒關係,此時去檢視安裝目錄下的log錯誤日誌檔案,就能發現錯誤資訊啦。接下來就是根據錯誤資訊修改程式啦,這個就各有各的區別了。