如何打开原始路径C#的几个级别的目录?

时间:2011-11-08 21:08:18

标签: c#

我需要在应用程序执行的位置打开3级文件夹(原始示例我有一些缺陷):

        // find the path where the executable resides
        string dbPath = Application.StartupPath;

        // constructing the connection string - double slashes
        string connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
            + dbPath + "\\..\\..\\..\\Magazines.accdb; User Id=admin; Password=";

但这会打开:

C:\Documents and Settings\Server\Desktop\Lab 10\Lab 10\Lab 10\bin\Debug\..\..\..\Magazines.accdb

程序开始的原始目录:

C:\Documents and Settings\Server\Desktop\Lab 10\Lab 10\Lab 10\bin\Debug\

我需要它:

C:\Documents and Settings\Server\Desktop\Lab 10\Lab 10\Magazines.accdb

这样做的恰当之处是什么?

3 个答案:

答案 0 :(得分:3)

使用DirectoryInfo评估'..

 var path = new DirectoryInfo (Path.Combine( "c:/bla", "../newBla")).FullName()

同时使用Path.Combine进行更轻松,更可靠的组合。

答案 1 :(得分:2)

更改Magazines.accdb的属性,以便在构建项目时将其复制到bin \ Debug文件夹。

您可以通过右键单击解决方案资源管理器中的文件,然后将“复制到输出目录”更改为“始终复制”来执行此操作。

答案 2 :(得分:0)

几个选项只是将您的数据库放在与可执行文件相同的文件夹中(因此,在您的调试文件夹中),这实际上是有意义的,因为当您将可执行文件打包给通常具有生成的文件夹结构的人时。

另一种选择是,如果将数据库文件添加到项目中,则可以将“复制到输出目录”指定为“如果更新则复制”,如果更新则复制。