views:

74

answers:

4

Hello,

This might seem an easy question for some, but I am struggling with it.

I am trying to use SQLDataReader.GetFieldType to check if a certain field is an Image field. Lets assume the first field of the result set is an Image field, if I do:

reader.GetFieldType(0).ToString;

I get System.Byte[] But is this the correct way to check for it? I really don't like:

if (reader.GetFieldType(0).ToString="System.Byte[]")

Is there a better way?

Thanks,

AJ

+1  A: 

It's preferable to use the Type.IsAssignableFrom method instead of looking at the type name itself.

Type fieldType = reader.GetFieldType(0);
bool isImageField = typeof(byte[]).IsAssignableFrom(fieldType);

This gives you some measure of compile-time safety.

Note: This doesn't actually guarantee that the field will contain images - any form of binary data can be stored in image/binary/varbinary fields, so the only way to see if it is truly an image is to read the value and try loading it as one. But you can use this to check if the field is a binary field.

Aaronaught
A: 

You might have to check for the first bytes to see if they make an image header. Otherwise, you might deal with an audio file, for instance. So a byte array doesn't necessarily represent an image.

thelost
+4  A: 

You could always shorten it a bit:

if(reader.GetFieldType(0) == typeof(byte[]));

Unfortunately there's no direct mapping from an image field in SQL Server to a .NET CLR type...which is why you get a byte array.

You might want to add further checking to make sure that the byte array being returned is actually an image (byte arrays are used for image, binary, varbinary, and rowversion columns as well).

You can check the type mappings at:

MSDN - Mapping CLR Parameter Data

Justin Niessner
+1 for using typeof(byte[]) to avoid the hardcoded type name.
ydobonmai
+1  A: 

An alternative way could be to use the SqlDataReader.GetSchemaTable method. This will return a datatable containing the schema of the resultset, and makes available the actual datatype from the db - e.g. the DataTypeName column of the schema table returned will be the actual SQL Server datatype like varchar, and the ProviderSpecificDataType column will be a System.Data.SqlType

e.g.

DataTable dataSchema = reader.GetSchemaTable();
// dataSchema.Rows[0]["DataTypeName"] would return the sql server 
// data type name for the first column in the resultset.
AdaTheDev