0

I'm trying to close a database and then delete the database file. After executing procedures like:

string sql = @"SELECT * FROM comments WHERE name=@name";

var command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.Add(new SQLiteParameter("@name", name));

SQLiteDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
    reader.Read();
    return reader.GetString(1);
}
else 
    return "";

I initiate a method the starts:

m_dbConnection.Close();

if (System.IO.File.Exists("MyDatabase.sqlite"))
    System.IO.File.Delete("MyDatabase.sqlite");

This latter code, however, generates an IOException:

The process cannot access the file [filepath] because it is being used by another process.

The error message seems self-explanatory (and I did look at this SO post on the topic), but I guess I don't understand how to stop using the file so I can delete it.

Community
  • 1
  • 1
Al C
  • 5,175
  • 6
  • 44
  • 74

1 Answers1

0

Always use using to ensure that the database objects are properly disposed of:

using (var command = new SQLiteCommand(sql, m_dbConnection))
using (var reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        reader.Read();
        return reader.GetString(1);
    }
    else 
        return "";
}
CL.
  • 173,858
  • 17
  • 217
  • 259
  • Thank you for taking the time to respond. I looked up the documentation on the `using` statement and will definitely "use" it (ha ha) from now on. – Al C Jan 11 '17 at 21:02