2016-07-22 88 views
1

SQLiteConnection.Open在打开不是数据库的文件时不会引发异常。如何检查文件是否是C#中的SQLite数据库?

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

回答

4

阅读前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"); 
+1

@你可以在上面的代码中传递文件路径,并检查返回的字符串,如果包含“SQLite格式”,那么你的文件是一个SQLite数据库。请检查这是否适合你。 – Maverick

+0

你为什么要创建一个包含17个字节的数组? – Ben

+1

@这是因为在VB中,数组的大小被声明为数组的上限,其中大多数语言(包括C#)通过指定数组中元素的数量来声明数组的大小。 – Maverick

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; 
    } 
相关问题