views:

136

answers:

2

I want my connection to the database to be available all the time, so if i move the folder with the project, to an other computer, the connection to be made automaticaly. So, how can i change this connection:

this.oleDbConnection1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Documents and Settings\\Cristi\\Do" +
                "cuments\\Visual Studio 2008\\Projects\\WindowsApplication3\\bd1.mdb\"";

??? It should read the project directory or something. I don't know. Any ideas? Thank You!

A: 

Sounds like you want to use a relative path in your connection string.

Something like this:

this.oleDbConnection1.ConnectionString = 
"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + 
Server.MapPath("~\\MyData\\MyDatabase.mdb"); 

This will correspond to the /MyData directory within your application. Be aware of the security concern that the .mdb file may be visible to [un]intentional foul play.

Bob Kaufman
Error 102 The name 'Server' does not exist in the current context Ty for your quick reply!
Bomboe Cristian
A: 

If you add the access database to the project, and in the file properties set the Copy to Output Directory property to Copy Always (or Copy if Newer if appropriate), you can use a connection string similar to this:

this.oleDbConnection1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\".\\bd1.mdb\""; 

This will work because the database will be located in the same folder as your binaries.

Similarly, you could use a relative path to your database, relative to where the executing assembly is located.

Paul Kearney - pk
yes, this is exactly what i want to do. i added the database to the project. Where should i put it? in the debug folder? or were the .sln is located? And please explain this:"file properties set the Copy to Output Directory property to Copy Always (or Copy if Newer if appropriate)" please. file properties of the . mdb? i don't understand. Thank You!
Bomboe Cristian
You can put it anywhere you like. Perhaps you'd want to keep it in a separate folder, say called Data, under your project folder. For the file properties, right click the MDB file in Solution Explorer and choose Properties. In the property pane, you'll see a property called "Copy to Output Directory". Pick an option from the list that is appropriate for your situation.
Paul Kearney - pk
But for a production app, is not the binary folder going to be in the Programs folder? That is a read-only location for regular users, and for everybody under UAC in Vista/Win7, and thus, you don't want to store your data file there.
David-W-Fenton