Reputation: 839
Sorry if this's been already asked! I am able to attach a mssql database on button click using this code:
using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=;Integrated Security=True; MultipleActiveResultSets = true"))
{
using (SqlCommand cmd = new SqlCommand("", connection))
{
using (SqlCommand cmd1 = new SqlCommand("", connection))
{
try
{
cmd.CommandText = "CREATE DATABASE [TRTF_TagLogging] ON (FILENAME ='C:\\Release\\App_Data\\TRTF_TagLogging.mdf'),(FILENAME ='C:\\Release\\App_Data\\App_Data\\TRTF_TagLogging_log.ldf') FOR ATTACH";
cmd1.CommandText = "if(exists(select * from sys.databases where name = 'TRTF_TagLogging')) PRINT 'DB attached'";
connection.Open();
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
//the rest of the code
I would like to be able to attach the db using a relative path. Meaning that instead of using 'C:\Release\App_Data\TRTF_TagLogging.mdf', I should use '.\App_Data\TRTF_TagLogging.mdf'.
Using '.\App_Data\TRTF_TagLogging.mdf', I get 'System.Data.SqlClient.SqlException (0x80131904): A file activation error occurred. The physical file name '.\App_Data\TRTF_TagLogging.mdf' may be incorrect.'
Upvotes: 0
Views: 118
Reputation: 839
If anyone else is interested, I managed to solve it like this:
string path = Directory.GetCurrentDirectory();
cmd.CommandText = @"CREATE DATABASE [TRTF_TagLogging] ON (FILENAME ='" + path + @"\App_Data\TRTF_TagLogging.mdf'),(FILENAME ='" + path + @"\App_Data\TRTF_TagLogging_log.ldf') FOR ATTACH";
Directory.GetCurrentDirectory()
returns, in my case, C:\Release.
Upvotes: 1