获取 Windows 表单应用程序中的当前路径无法正常工作

Getting current path in Windows form application not working properly

我正在开发一个链接到本地​​数据库的应用程序,我想获取数据库 dynamically 的路径。我不知道用户会在哪里复制这个应用程序,所以我想自动获取数据库的路径。我写了下面的代码,它获取了路径,但不完全是。我的意思是,如果我有我的应用程序: 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");