Victor
Victor

Reputation: 1108

How to specify a sql connection string on c# that will always work even if you change directory?

I have a connection string on a ASP.NET Solution...

Data Source=.\SQLEXPRESS;AttachDbFilename="F:\Prueba Documento Digital\Prueba Documento Digital\App_Data\BaseDeDatos.mdf";Integrated Security=True;User Instance=True

You may notice that it specifies an exact route because is located on mys USB Flash Drive, but what would happen if I move my solution to another place (Prueba Documento Digital is the name of the solution)?

I was trying something like ~/App_Data... but it didn't work... What can be done?

Upvotes: 1

Views: 936

Answers (4)

Aaron Bertrand
Aaron Bertrand

Reputation: 280570

Just stop using the AttachDbFileName property and the deprecated User Instance feature in the first place. Do you really want to create a new copy of your database every time you start your application?

Instead, create your database directly on the actual Express instance, using CREATE DATABASE BaseDeDatos ... FOR ATTACH .... Then your application will always be referring to the proper copy of your database (I strongly recommend not moving your .mdf file around on a USB flash drive - if you want portable development, use Azure or something):

Data Source=.\SQLEXPRESS;Initial Catalog=BaseDeDatos;Integrated Security=True;

Upvotes: 1

Ravindra Bagale
Ravindra Bagale

Reputation: 17675

it's simple, give server address, & in that access your data directory & mention database filename. put your database file in App_Data folder

Data Source=.\SQLEXPRESS;AttachDbFilename=|dataDirectory|\BaseDeDatos.mdf;Integrated Security=True;User Instance=True.

in this code, AttachDbFilename searches for database file named BaseDeDatos.mdf

Upvotes: 1

DreamsDotNet
DreamsDotNet

Reputation: 48

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BaseDeDatos.mdf;Integrated Security=True;User Instance=True

Upvotes: 2

scartag
scartag

Reputation: 17680

You can put the Database in the App_Data folder and access it via the DataDirectory

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BaseDeDatos.mdf;Integrated Security=True;User Instance=True

By default asp.net will check the App_Data folder when it sees the DataDirectory directive (except you change the DataDirectory by calling AppDomain.SetData)

Upvotes: 3

Related Questions