簡體   English   中英

在Windows窗體應用程序中獲取當前路徑無法正常工作

[英]Getting current path in Windows form application not working properly

我正在鏈接到本地數據庫的應用程序,我想獲得分貝d y的路徑namically。 我不知道用戶將在哪里精確復制此應用程序,因此我想自動獲取數據庫的路徑。 我編寫了以下代碼,它獲取了路徑,但不完全是。 我的意思是,如果我的應用程序位於: C:\\Users\\ROG\\Desktop ,則表示C:\\Users\\ROG沒有數據庫。 因此它沒有得到它的最后位置。 為什么會這樣以及如何解決呢?

我將其連接如下:

var connString = (@"Data Source=" + 
                  Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + 
                  @"\Angajati.sdf");

嘗試使用以下代碼

var connString = (@"Data Source=" + 
                  System.IO.Path.Combine(System.IO.Path.GetDirectoryName(
                         System.Reflection.Assembly.GetExecutingAssembly().Location),
                  "Angajati.sdf"));

建議不要使用“獲取當前目錄”,而應使用“應用程序路徑”。 這是因為如果使用OpenFileDialog則當前目錄會更改,但是applicationPath是相同的。

System.Reflection.Assembly.GetExecutingAssembly().Location

希望對您有所幫助。

考慮使用以下代碼來確定應用基本目錄:

AppDomain.CurrentDomain.BaseDirectory

完整的代碼如下所示:

var connString = "Data Source=" + 
              System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Angajati.sdf");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM