简体   繁体   中英

How to open directory few levels down of original path C#?

I need to open a folder 3 levels down from where application executes (original example I had have some flaws):

        // 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=";

But this will open:

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

Original directory from where program starts:

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

And I need it to be:

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

What is the proper was of doing this?

Use DirectoryInfo for evaluating the '..'

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

Also use Path.Combine for eased and more reliable combination.

Change the properties of Magazines.accdb so that it will be copied to the bin\\Debug folder when you build the project.

You can do this by right clicking file in solution explorer, then changing Copy to Output Directory to Copy always.

Couple options are to just put your database in the same folder as the executable (so, in your debug folder), this actually makes sense as when you package your executable to someone you would normally have the resulting folder structure.

Another option is if the database file is added to the project, you can specify the "Copy to Output Directory" to "Copy if Newer", which will copy if newer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM