检查文件是否是有效的SQLite数据库

时间:2014-03-08 21:11:23

标签: vb.net sqlite com interop

我需要检查文件(扩展名未知)是否是有效的SQLite数据库。

我的功能正常,但是当它失败时,退出函数后文件仍然被锁定:

Public Function IsSqliteDB(ByVal uPath As String) As Boolean

    'Workaround for my problem: Make a copy and work on this because this function is going to lock the file unfortunately
    Dim sNewPath As String
    sNewPath = Settings.Locations.Folder_LocalAppData_Temp & "\temp_" & Replace(Now.ToString, ":", "_") & ".db"

    modIO.FileForceCopy(uPath, sNewPath)

    Dim bIsSQLiteDB As Boolean = False

    Dim c As New dhRichClient3.cConnection
    Dim r As dhRichClient3.cRecordset


    Try
        Dim b As Boolean = c.OpenDB(sNewPath) 'returns true although this is not an sqlite-db. Can't do anything about it
        R = c.OpenRecordset("SELECT * FROM sqlite_master")
        bIsSQLiteDB = True

    Catch ex As Exception
        r = Nothing
        c = Nothing
    Finally
        r = Nothing
        c = Nothing
    End Try

    modIO.DeleteFile(sNewPath)'this fails. File is locked

    Return bIsSQLiteDB

End Function

有人看到我可以确保文件不再被锁定的位置吗?或者我真的必须使用该文件的副本,因为COM组件的行为并不是真的已知(不幸的是闭源)? 我确实可以使用备份,但文件可能非常大(> 1 GB),所以如果我能避免它,我想避免复制工作。

dhRichClient中没有“关闭”功能。我想,一旦cConection超出范围,就会在内部调用“关闭”。在函数末尾调用GC.Collect()没有帮助。

1 个答案:

答案 0 :(得分:4)

要确定文件是否是SQLite数据库,只需检查database header的前16个字节。

来自tmighty的评论:

Public Function IsSqliteDB(ByVal uPath As String) As Boolean
    Dim bytes(16) As Byte
    Using fs As New IO.FileStream(uPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        fs.Read(bytes, 0, 16)
    End Using
    Dim text As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
    Return text.Contains("SQLite format")
End Function