Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6327329
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T17:15:29+00:00 2026-05-24T17:15:29+00:00

Here is a complete program that creates a SQL Server Express database and removes

  • 0

Here is a complete program that creates a SQL Server Express database and removes it from the local instance, leaving a file-only database to play with. After playing with it, I want to delete it.

At the start of the Main method, I can delete the db files from previous runs successfully.

However if I try to delete them at the end of the Main method, the operation fails with

The process cannot access the file ‘c:\temp.mdf’ because it is being
used by another process.

According to http://blogs.msdn.com/b/sqlexpress/archive/2008/02/22/sql-express-behaviors-idle-time-resources-usage-auto-close-and-user-instances.aspx, with AUTO_CLOSE on as is default for SQL Server Express, after 300ms of idleness, SQL Server Express should release access to the file, but it appears this is not happening.

Does anyone know how I can get this to work so I can clean up after myself?

TIA

using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace ConsoleApplication3 {
class Program {

    private const string ConnectionStringToFile = @"Data Source=.\SqlExpress;Integrated Security=True;AttachDbFileName={0};User Instance=True";
    private const string ConnectionStringToTempDb = @"Data Source=.\SqlExpress;Initial Catalog=TempDb;Integrated Security=True;User Instance=True;";

    private const string CreateDbSql = "CREATE DATABASE {0} ON PRIMARY (NAME='{0}', FILENAME='{1}');";
    private const string DetachDbSql = "EXEC sp_detach_db '{0}', 'true';";

    private static SqlConnection GetConnection(string connectionString) {
        var conn = new SqlConnection(connectionString);
        Debug.WriteLine("Created", "Connection");
        Debug.Indent();
        conn.StateChange += ConnectionStateChange;
        conn.InfoMessage += ConnectionInfoMessage;
        conn.Disposed += ConnectionDisposed;
        return conn;
    }

    private static void ConnectionDisposed(object sender, EventArgs e) {
        SqlConnection conn = (SqlConnection)sender;
        conn.StateChange -= ConnectionStateChange;
        conn.InfoMessage += ConnectionInfoMessage;
        conn.Disposed += ConnectionDisposed;
        Debug.Unindent();
        Debug.WriteLine("Disposed", "Connection");
    }

    private static void ConnectionInfoMessage(object sender, SqlInfoMessageEventArgs e) {
        Debug.WriteLine("InfoMessage: " + e.Message, "Connection");
    }

    private static void ConnectionStateChange(object sender, System.Data.StateChangeEventArgs e) {
        Debug.WriteLine("StateChange: from " + e.OriginalState + " to " + e.CurrentState, "Connection");
    }

    static void Main() {

        const string DbName = "temp";
        const string DbPath = "c:\\temp.mdf";
        const string DbLogFile = "c:\\temp_log.ldf";

        if (File.Exists(DbPath)) File.Delete(DbPath);
        if (File.Exists(DbLogFile)) File.Delete(DbLogFile);

        using (var conn = GetConnection(ConnectionStringToTempDb)) {
            conn.Open();
            using (var command = conn.CreateCommand()) {
                command.CommandText = string.Format(CreateDbSql, DbName, DbPath);
                command.ExecuteNonQuery();
                command.CommandText = string.Format(DetachDbSql, DbName);
                Debug.WriteLine("Detach result: " + command.ExecuteScalar(), "Database"); 
            }
        }

        using (var conn = GetConnection(string.Format(ConnectionStringToFile, DbPath))) {
            conn.Open();
            using (var command = conn.CreateCommand()) {
                command.CommandText = "PRINT 'Successfully connected to database.'";
                command.ExecuteNonQuery();
                command.CommandText = "CREATE TABLE temp (temp int)";
                command.ExecuteNonQuery();
                command.CommandText = "INSERT temp VALUES (1);";
                command.ExecuteNonQuery();
            }
        }

        // takes 300ms apparently: http://blogs.msdn.com/b/sqlexpress/archive/2008/02/22/sql-express-behaviors-idle-time-resources-usage-auto-close-and-user-instances.aspx
        Thread.Sleep(1000);
        if (File.Exists(DbPath)) File.Delete(DbPath);
        if (File.Exists(DbLogFile)) File.Delete(DbLogFile);
    }
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T17:15:30+00:00Added an answer on May 24, 2026 at 5:15 pm

    I found the answer after trawling around the documentation. Just before closing the last connection to the database (or create one for the purpose), clear the connection pool using SqlConnection.ClearPool(SqlConnection connection) as shown below:

    using System;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.IO;
    using System.Threading;
    
    namespace ConsoleApplication3 {
      class Program {
    
        private const string ConnectionStringToFile = @"Data Source=.\SqlExpress;Integrated Security=True;AttachDbFileName={0};User Instance=True";
        private const string ConnectionStringToTempDb = @"Data Source=.\SqlExpress;Initial Catalog=TempDb;Integrated Security=True;User Instance=True;";
    
        private const string CreateDbSql = "CREATE DATABASE {0} ON PRIMARY (NAME='{0}', FILENAME='{1}');";
        private const string DetachDbSql = "EXEC sp_detach_db '{0}', 'true';";
    
        private static SqlConnection GetConnection(string connectionString) {
          var conn = new SqlConnection(connectionString);
          Debug.WriteLine("Created", "Connection");
          Debug.Indent();
          conn.StateChange += ConnectionStateChange;
          conn.InfoMessage += ConnectionInfoMessage;
          conn.Disposed += ConnectionDisposed;
          return conn;
        }
    
        private static void ConnectionDisposed(object sender, EventArgs e) {
          SqlConnection conn = (SqlConnection)sender;
          conn.StateChange -= ConnectionStateChange;
          conn.InfoMessage += ConnectionInfoMessage;
          conn.Disposed += ConnectionDisposed;
          Debug.Unindent();
          Debug.WriteLine("Disposed", "Connection");
        }
    
        private static void ConnectionInfoMessage(object sender, SqlInfoMessageEventArgs e) {  
          Debug.WriteLine("InfoMessage: " + e.Message, "Connection");
        }
    
        private static void ConnectionStateChange(object sender, System.Data.StateChangeEventArgs e) {
          Debug.WriteLine("StateChange: from " + e.OriginalState + " to " + e.CurrentState, "Connection");
        }
    
        static void Main() {
    
          const string DbName = "temp";
          const string DbPath = "c:\\temp.mdf";
          const string DbLogFile = "c:\\temp_log.ldf";
    
          using (var conn = GetConnection(ConnectionStringToTempDb)) {
            conn.Open();
            using (var command = conn.CreateCommand()) {
              command.CommandText = string.Format(CreateDbSql, DbName, DbPath);
              command.ExecuteNonQuery();
              command.CommandText = string.Format(DetachDbSql, DbName);
              Debug.WriteLine("Detach result: " + command.ExecuteScalar(), "Database"); 
            }
          }
    
          using (var conn = GetConnection(string.Format(ConnectionStringToFile, DbPath))) {
            conn.Open();
            using (var command = conn.CreateCommand()) {
              command.CommandText = "PRINT 'Successfully connected to database.'";
              command.ExecuteNonQuery();
              command.CommandText = "CREATE TABLE temp (temp int)";
              command.ExecuteNonQuery();
              command.CommandText = "INSERT temp VALUES (1);";
              command.ExecuteNonQuery();
            }
            SqlConnection.ClearPool(conn);
          }
    
          // SqlExpress takes 300ms to go idle:
          // http://blogs.msdn.com/b/sqlexpress/archive/2008/02/22/sql-express-behaviors-idle-time-resources-usage-auto-close-and-user-instances.aspx
          Thread.Sleep(500); // wait for 500ms just in case (seems to work with 300 though).
          if (File.Exists(DbPath)) File.Delete(DbPath);
          if (File.Exists(DbLogFile)) File.Delete(DbLogFile);
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm reading a file from a SQL server and writing it to disk temporarily
Here is a complete example. I want to forbid using A::set from objects casted
I have a program in Python that gets a window handle via COM from
Here's my statement from my C# program: (edit by gbn, formatted for clarity so
Here is the complete install command to CPAN and the output: sudo perl -MCPAN
complete noob to Haskell here with probably an even noobier question. I'm trying to
Here is my code. The complete binary tree has 2^k nodes at depth k.
The current form is here . It is not complete, and only a couple
Ok, here goes. I've completed a Cocoa foundation-tool that calculates mean absolute deviation of
Here's a basic regex technique that I've never managed to remember. Let's say I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.