How to tell if sqlite database file is valid or not

Viewed 10713

In the code below, pathToNonDatabase is the path to a simple text file, not a real sqlite database. I was hoping for sqlite3_open to detect that, but it doesn't (db is not NULL, and result is SQLITE_OK). So, how to detect that a file is not a valid sqlite database?

sqlite3 *db = NULL;
int result = sqlite3_open(pathToNonDatabase, &db);

if((NULL==db) || (result!=SQLITE_OK)) { 
   // invalid database
}
4 Answers

If you want only to check if the file is a valid sqlite database then you can check with this function:

    private bool CheckIfValidSQLiteDatabase(string databaseFilePath)
    {
        byte[] bytes = new byte[16];
        using (FileStream fileStream = new FileStream(databaseFilePath, FileMode.Open, FileAccess.Read))
        {
            fileStream.Read(bytes, 0, 16);
        }
        string gg = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
        return gg.Contains("SQLite format");
    }

as stated in the documentation: sqlite database header

Related