Search code examples
c#sqlite

SQLite in C# throws "InvalidCastException" using .GetBytes


I am trying to access a column of Blob's in an SQLite DB which will eventually be pointers to a record on a file or in memory. I'm trying to use the .GetBytes method in SQLite to get an array of bytes that will represent my data. I keep getting an InvalidCastException while using this method. Everything seems to be in place and the program compiles just fine, but during runtime this exception keeps getting thrown. I've looked around for answers and everything seems to agree with the code I have so I am at a loss here, and unfortunately I can't find any good documentation for SQLite in C#. Code is as follows

  public byte[] Output()
    {
        byte[] temp = null;
        int col = Columns + 1;
        if(read.Read())
        {
            read.GetBytes(col, 0, temp, 0, 2048); //exception is thrown here
        }
        return temp;
    }

I've been able to read other columns in the DB that are ints and texts, but for some reason can't seem to get the blobs right.

EDIT: new info, Here is the stack trace from the exception:

     StackTrace:
   at System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
   at System.Data.SQLite.SQLiteDataReader.GetBytes(Int32 i, Int64 fieldOffset, Byte[] buffer, Int32 bufferoffset, Int32 length)
   at SQLiteSort.Sort.Output() in C:\Users\cjones\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Sort.cs:line 192
   at SQLiteSort.Sort.Main(String[] args) in C:\Users\cjones\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Sort.cs:line 72
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

InnerException:

The exception seems to be thrown by SQLiteDataReader.VerifyType(), this is looking at the column being used for a DbType.Binary type and throws an exception if the column is not a DbType.Binary, DbType.String, or DbType.Guid. I've checked the table over and over and it still shows the column type as a blob.


Solution

  • Well I finally fixed the problem by using parameter's and setting my Blob to DbType.Binary. Not sure why this is so different from what I was doing before but everything is working as it should now.