Attach database programmatically
<p>I have a login form in my project and I write below code to attach my database( there is in d:\ ) when this login form loads:</p>
<pre><code>try
{ 
    SqlConnection con = new SqlConnection(@&quot;Data Source=.;Initial Catalog=master;Integrated Security=True&quot;);
    con.Open();

    SqlDataAdapter da = new SqlDataAdapter(&quot;select name from sys.databases&quot;, con);
    DataTable dt = new DataTable();
    da.Fill(dt);

    string[] array = dt
        .AsEnumerable()
        .Select(row =&gt; row.Field&lt;string&gt;(&quot;Name&quot;))
        .ToArray();

    if (!array.Contains(&quot;cstmrDB&quot;, StringComparer.OrdinalIgnoreCase))
    {
        SqlCommand cmd = new SqlCommand(&quot;sp_attach_db&quot;);
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue(&quot;@dbname&quot;, &quot;Apdb&quot;);
        cmd.Parameters.AddWithValue(&quot;@filename1&quot;, @&quot;d:\Apdb.mdf&quot;);
        cmd.ExecuteNonQuery();

    }
}
catch (exception ex) 
{ 
    messagebox.show(ex.message); 
}
</code></pre>
<p>It works fine in my laptop.  I publish my project (using c# publish) and install SQL Server and my project and copy my database in d:\ in another PC. but when i run my project, the database won't attach!  I don't know why this problem occurrs... but I think maybe the reason is that I don't write any code to define *.ldf file (but i put both mdf and ldf file in d:\ )</p>
<blockquote>
<p>ERROR: A network-related or instance-specific error occurred while establishing a connection to SQL Server.</p>
<p>The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.</p>
<p>(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)</p>
</blockquote>