如何检查文件是否是C#中的SQLite数据库?

时间:2016-07-22 06:33:36

标签: c# sqlite

打开不是数据库的文件时,SQLiteConnection.Open不会抛出异常。

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

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

如何确定文件是否是SQLite数据库?

2 个答案:

答案 0 :(得分:4)

读取前16个字节,然后检查字符串“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")

更新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");

答案 1 :(得分:0)

    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;
    }