【问题标题】:How do I check if a file is a SQLite Database in C#?如何检查文件是否是 C# 中的 SQLite 数据库?
【发布时间】:2016-07-27 01:16:31
【问题描述】:

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 数据库?

【问题讨论】:

    标签: c# sqlite


    【解决方案1】:

    读取前 16 个字节,然后检查字符串“SQLite 格式”

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

    【讨论】:

    • @Ben 您可以在上述代码中传递文件路径并检查返回的字符串,如果其中包含“SQLite 格式”,则您的文件是 SQLite 数据库。请检查这是否适合您。
    • 为什么要创建一个包含 17 个字节的数组?
    • @Ben 这是因为在 VB 中,数组的大小是用数组的上限声明的,而大多数语言(包括 C#)通过指定数组中元素的数量来声明数组的大小数组。
    【解决方案2】:
        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;
        }
    

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 2011-10-29
      • 2014-04-03
      • 2011-03-04
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      相关资源
      最近更新 更多