首頁>技術>

記錄平時發現並解決的相關問題。

問題場景

當前編寫的應用程式在啟動時,需要載入配置檔案,並在程式開啟時載入配置檔案中的url,載入失敗時丟擲載入失敗的異常資訊。

報錯提示找不到相關的配置檔案:

問題分析

透過異常堆疊資訊確認是配置檔案載入失敗,相關程式碼獲取配置檔案程式碼如下:

/// <summary>/// 預設頁面URL配置檔案/// </summary>public static string indexUrlFile = "Resource/Config/station.xml";/// <summary>/// 獲取預設介面URL/// </summary>/// <returns></returns>public static string GetIndexUrl(){  XmlDocument XmlDoc = new XmlDocument();  if (!File.Exists(indexUrlFile))  {    throw new Exception("配置檔案不存在");  }  XmlDoc.Load(urlPath);  if(XmlDoc == null)  {    throw new Exception("配置檔案讀取失敗");  }  XmlNodeList indexList = XmlDoc.GetElementsByTagName("index");  if(indexList.Count == 0 || indexList[0].Attributes.Count == 0 )  {    throw new Exception("配置檔案格式不正確");  }  url = indexList[0].Attributes[0].Value;  if (string.IsNullOrEmpty(url))  {    throw new Exception("配置檔案格式不正確");  }  return url;}

透過檢視程式碼確認配置檔案的路徑為相對路徑:"Resource/Config/station.xml",同時透過問題場景確認,在工作列點選快捷圖示時,程式啟動時獲取到的路徑為桌面路徑,在桌面路徑下去查詢檔案"Resource/Config/station.xml",而桌面路徑下當然不可能存在對應的檔案。

解決方案

問題是由於程式啟動時根據當前程式的預設目錄下再去查詢配置檔案"Resource/Config/station.xml",這時由於快捷方式啟動時指向的預設目錄不同就可能會導致配置檔案載入失敗的情況。

為了解決這個問題,程式啟動時載入配置檔案需要使用絕對路徑獲取配置檔案資訊,這時不管程式啟動時預設指向的是哪個目錄,只要能夠定位到程式的安裝目錄就能夠獲取到配置檔案資訊。

修改程式碼如下:

/// <summary>/// 預設頁面URL配置檔案/// </summary>public static string indexUrlFile = "Resource/Config/station.xml";/// <summary>/// 獲取預設介面URL/// </summary>/// <returns></returns>public static string GetIndexUrl(){  string url = "";  string urlPath = Path.Combine(System.Windows.Forms.Application.StartupPath, indexUrlFile);  XmlDocument XmlDoc = new XmlDocument();  if (!File.Exists(urlPath))  {    throw new Exception("配置檔案不存在");  }  XmlDoc.Load(urlPath);  if(XmlDoc == null)  {    throw new Exception("配置檔案讀取失敗");  }  XmlNodeList indexList = XmlDoc.GetElementsByTagName("index");  if(indexList.Count == 0 || indexList[0].Attributes.Count == 0 )  {    throw new Exception("配置檔案格式不正確");  }  url = indexList[0].Attributes[0].Value;  if (string.IsNullOrEmpty(url))  {    throw new Exception("配置檔案格式不正確");  }  return url;}

這裡透過System.Windows.Forms.Application.StartupPath獲取啟動了應用程式的可執行檔案的路徑,不包括可執行檔案的名稱,然後再拼接配置檔案資訊,這時就可以透過絕對路徑獲取到配置檔案資訊。

這樣在工作列透過快捷方式也能夠正常開啟程式了。

獲取程式執行路徑的常用方法

方法

獲取路徑

System.Windows.Forms.Application.StartupPath

獲取啟動了應用程式的可執行檔案的路徑,不包括可執行檔案的名稱

System.Windows.Forms.Application.ExecutablePath

獲取啟動了應用程式的可執行檔案的路徑,包括可執行檔案的名稱

System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

獲取包含該應用程式的目錄的名稱

13
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 2021,Swift的JSON-Model轉換還有什麼新花樣