Database connection cannot be closed, DB cannot be copied

Hi,

I want to copy my database from my application. I got an error message that said the file was in use.

I checked my code, I acturally closed the connection before copying the database. My code is as followed.

SqlConnection conn = new SqlConnection(DBConnectionString);
SqlCommand sql = new SqlCommand("select DataVersion from globalData", conn);
conn.Open();
SqlDataReader sqlreader = sql.ExecuteReader();
if (sqlreader.Read())
{
userDBVerion = Convert.ToInt32(sqlreader["DataVersion"].ToString());
}
else
DocShare.userDBVerion = 1;
sqlreader.Close();
sql.Connection.Close();
conn.Close();
//conn.dispose();//I tried this one as well, no help

Thanks

clinicalcom



Answer this question

Database connection cannot be closed, DB cannot be copied

  • mranzani

    why dont you try a "try catch finally block" that would ensure you db is closed i think

  • Giber

    try the following construct

    SqlConnection connection = null;
    try
    {
           connection =
    new SqlConnection("connection stirng here");
           SqlCommand cmd = new SqlCommand("command here", connection);
           using (SqlDataReader reader = cmd.ExecuteReader())
           {
                  //read here
           } //reader is closed here
    }
    catch (SqlException ex)
    {
         //log error
    }
    finally
    {
            if ((null != connection) && (connection.State != ConnectionState.Closed))
              connection.Close();
    }

    Hope this helps



  • technica

    clinicalcom wrote:

    sql.Connection.Close();

    What is it It seems no such class or use.



  • Database connection cannot be closed, DB cannot be copied