ilitirit
ilitirit

Reputation: 16352

Reading an image from the database using C#?

I've got this query:

SELECT PICTURE FROM LOGO WHERE LOGONO = ?

("PICTURE" is an Image column in SQL Server)

And this code to read the data:

using (DbDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        if (!reader.IsDBNull(0))
        {
            byte[] buffer = new byte[8000];
            while (reader.GetBytes(0, 0, buffer, 0, 8000) > 0)
                picture.AddRange(buffer);
        }
     }
}

The problem is an InvalidOperationException ("No data exists for the row/column") always gets thrown on the reader.IsDBNull(0) statement when the column contains null.

MSDN says:

Call this method to see if there are null column values before calling the typed get methods (for example, GetByte, GetChar, and so on) to avoid raising an error.

How can I check that the column doesn't contain null without triggering the Exception? Am I going about this in the wrong way?

Upvotes: 1

Views: 2116

Answers (4)

JPabon
JPabon

Reputation: 11

Isn't better...

if (!reader.IsDBNull(#))
{...}

or perhaps the short version...

reader.IsDBNull(#) ? [default] : [value];

???

Upvotes: 1

Cody C
Cody C

Reputation: 4807

I always use the following check and it seems to have always worked for me.

if (reader[0] != null && reader[0] != DBNull.Value)
{
}

Upvotes: 0

adrianbanks
adrianbanks

Reputation: 83004

You need to call reader.Read() before accessing any data. From the MSDN docs for Read:

The default position of the DataTableReader is before the first record. Therefore, you must call Read to start accessing any data.

Upvotes: 8

jrista
jrista

Reputation: 33010

You did not call reader.Read(). Since your working with a reader, you either need to check if Read returns true for a single record, or use a while loop to iterate through all the records.

if (reader.Read())
{
  // handle single record
}

// or

while (reader.Read())
{
  // handle each record
}

Upvotes: 2

Related Questions