I was wanting a method that would quickly and efficiently check to see if a file was a SQLite database. I put together a method that reads the first 16 bytes of a file and checks to see if header information SQLite would have is there. This isn't fullproof and doesn't check the validity of the database file itself. A header section of a SQLite database will contain SQLite format
is the first 16 bytes (I did not care about the version). Obviously if a text file contains SQLite format in the first 16 bytes it would throw a false positive (but for my purposes this is quick and does exactly what I want).
VB.Net
''' <summary>
''' Does a quick check on a file to see if a valid SQLite header exists. This does not further check the validity
''' of the database. If the file does not exist, false will be returned.
''' </summary>
''' <param name="filename"></param>
Public Shared Function IsSqliteDatabase(filename As String) As Boolean
If System.IO.File.Exists(filename) = False Then
Return False
End If
' FileShare.ReadWrite allows to the file to be read even if it's locked by another process such as something
' that has an active connection to the database.
Using fs As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim bytes(16) As Byte
Dim x As Integer = fs.Read(bytes, 0, 16)
fs.Close()
Dim text As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Return text.Contains("SQLite format")
End Using
End Function
C#
/// <summary>
/// Does a quick check on a file to see if a valid SQLite header exists. This does not further check the validity
/// of the database. If the file does not exist, false will be returned.
/// </summary>
/// <param name="filename"></param>
public static bool IsSqliteDatabase(string filename)
{
if (System.IO.File.Exists(filename) == false)
{
return false;
}
// FileShare.ReadWrite allows to the file to be read even if it's locked by another process such as something
// that has an active connection to the database.
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] bytes = new byte[16];
int x = fs.Read(bytes, 0, 16);
fs.Close();
string text = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
return text.Contains("SQLite format");
}
}