I have finished building an application.
The last thing on my list was to put the SQL connection string in a file, rather than hardcoded (so that the user can edit it if ever need be).
The connection fails and I get an exception from DataContext.
The connection string is definitley correct. The only thing that has changed, since it was all working, is that I have put the connection string in a txt file rather than hard code it.
BEFORE (my app connected to database fine):
private string conString = "Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True";
public LogIn()
{
dc = new MyDataContext(conString);
if (dc.DatabaseExists())
{
InitializeComponent();
}
else
{
MessageBox.Show("There has been an error, please try again. If ther problem persists, call you know who. Error: Can't connect to database! Make sure the network is all good (connection to ADMIN PC)" /*+ e.ToString()*/);
}
}
NOW (NOT WORKING):
private string conString;
public LogIn()
{
try
{
ConnectionString.globalConString = System.IO.File.ReadAllText("connString.txt").ToString();
this.conString = ConnectionString.globalConString;
}
catch (IOException e)
{
MessageBox.Show("There was an error reading the conn string file.");
return;
}
dc = new MyDataContext(conString);
if (dc.DatabaseExists())
{
InitializeComponent();
}
else
{
MessageBox.Show("There has been an error, please try again. If ther problem persists, call you know who. Error: Can't connect to database! Make sure the network is all good (connection to ADMIN PC)" /*+ e.ToString()*/);
}
}
The txt file simply contains:
Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True
The file is in the correct location and the app can read it (I have outputted the string with MessageBox.Show()).
All I can think is that the string is not actually a string and is actually some strange format? I dunno.
BTW, the exception is thrown by the bit that tries to connect (not by the file reading bit - the code reads the file, but DataContext doesn't like the string that is passed to it).
Any ideas??
Thanks
Try removing the double \\
after HP
:
Data Source=HP\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True
The double backslash would have been valid when defining a C# string, because you'd need to escape the backslash character, but when read from a file, it would be viewed as two backslash characters.