Up till now I’ve been using the following connection string:
public static String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Ahmad\documents\visual studio 2010\Projects\DBtestApp1\DBtestApp1\TestDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
However, since the MDF file is in the same directory as the EXE running itself, and since this directory can change, I now was to retrieve the current directory using Directory.GetCurrentDirectory() ..
The problem is, a string assignment such as this does not work:
connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=\"" + currentDirectory + "TestDB.mdf\";Integrated Security=True;Connect Timeout=30;User Instance=True";
where currentDirectory holds the output of Directory.GetCurrentDirectory() ..
So whats the solution ?
This should actually work, but depending on the return value of
Directory.GetCurrentDirectory()your path might be broken.Instead of concatenating the path within your string, you should use
Path.Combine()provided insideSystem.IOfor this, which will handle additional/missing backslashes between the parts to be concatenated:You should then be able to simply add this string to your full connection string, which might be done using
String.Format()as well:I haven’t tried this, but shouldn’t it work using just
.\TestDB.mdfas the filename? Or does it have to be an absolute path?