Ben
Ben

Reputation: 2269

How do I check if a file is a SQLite Database in C#?

SQLiteConnection.Open does not throw exception when opening a file that is not a database.

private void openDatabase()
{
    sqlite = new SQLiteConnection("Data Source=" + this.filePath + ";Version=3;");

    try
    {
        sqlite.Open();
    }
    catch(SQLiteException e)
    {
        MessageBox.Show(e.Message + e.StackTrace);
    }
}

How do I determine if a file is a SQLite Database?

Upvotes: 2

Views: 2404

Answers (2)

Ben
Ben

Reputation: 2269

    public static bool isSQLiteDatabase(string pathToFile)
    {
        bool result = false;

        if (File.Exists(pathToFile)) {

            using (FileStream stream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                byte[] header = new byte[16];

                for (int i = 0; i < 16; i++)
                {
                    header[i] = (byte)stream.ReadByte();
                }

                result = System.Text.Encoding.UTF8.GetString(header).Contains("SQLite format 3");

                stream.Close();
            }

        }

        return result;
    }

Upvotes: 3

Maverick
Maverick

Reputation: 1434

Read the first 16 bytes and then check for the string "SQLite Format"

VB.Net

    Dim bytes(16) As Byte
    Using fs As New IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        fs.Read(bytes, 0, 16)
    End Using
    Dim chkStr As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
    Return chkStr.Contains("SQLite format")

Update 2

C#

    byte[] bytes = new byte[17];
    using (IO.FileStream fs = new IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
    fs.Read(bytes, 0, 16);
    }
    string chkStr = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
    return chkStr.Contains("SQLite format");

Upvotes: 4

Related Questions