onurcano
onurcano

Reputation: 415

How can I use variable in connection string?

I'm having trouble with variables for connection strings. In my app.config database path seems fine but on form, I'm getting error for that connection string. When I try to add:

_connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
    "AttachDbFilename = \"|DataDirectory|\\gazi_db.mdf\"; " +
    "Integrated Security = True; Connect Timeout = 30";

the database won't work correctly; it can't save data on exit. However this Works fine:

connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
        "AttachDbFilename = \"C:\\Users\\Can\\Desktop\\c_sharp_gazi_installer" +
        "\\Gazi Installer\\gazi_installer\\gazi_db.mdf\"; " +
        "Integrated Security = True; Connect Timeout = 30";

How can I fix this?

EDIT: I hoped this would work

string DataDirectory = "";
string folder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().CodeBase);
AppDomain.CurrentDomain.SetData("DataDirectory", folder);

_connectionString = _connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; " +
        "AttachDbFilename = \"" + DataDirectory + "\\gazi_db.mdf\"; " +
        "Integrated Security = True; Connect Timeout = 30";

But it's still giving me sqlclient sqlexception error.

EDIT2: This error indicates connection open. I don't understand why this doesn't work either:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Data Source"] = "(LocalDB)\\MSSQLLocalDB";
builder["AttachDbFilename"] = @"C:\Users\Can\\Desktop\c_sharp_gazi_installer\Gazi Installer\gazi_installer\gazi_db.mdf";
builder["Integrated Security"] = true;
builder["Connect Timeout"] = 30;

Please someone help. I'm going to go mad.

Upvotes: 0

Views: 5122

Answers (2)

Ragnarokkr Xia
Ragnarokkr Xia

Reputation: 201

Firstly, you can use the @ "symbol" to avoid using so many escape characters. Then, where did you define the "DataDirectory" variable?

Upvotes: 2

WereGoingOcean
WereGoingOcean

Reputation: 108

.NET has a connection string builder class. Using this you can set each value i.e. Data Source, Integrated Security separately to variables and then use the .ConnectionString property to get the connection string.

Upvotes: 1

Related Questions