Laurențiu Crețu
Laurențiu Crețu

Reputation: 1

SqlConnection string

I am trying to make a portable connection string with a service-based database.

If I use

C:\Users\X\Desktop\C# Projects\Windows Form Applications\PortableConnectionString\PortableConnectionString\BazaDate.mdf

and not |DataDirectory|BazaDate.mdf, it works.

What can I do to make it portable?

SqlConnection conn= new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BazaDate.mdf;Integrated Security=True;");
conn.Open();

Upvotes: 0

Views: 67

Answers (1)

joehoper
joehoper

Reputation: 423

Environment.GetCommandLineArgs()[0] is the full path of your executable, thus:

string appPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
string connStr = $@"Data Source=(LocalDB)\v11.0;AttachDbFilename={appPath}\BazaDate.mdf;Integrated Security=True;";

var conn = new SqlConnection(connStr);
conn.Open();

Upvotes: 2

Related Questions