2016-07-22 84 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; 
    } 
相關問題