How to check if a field is an Image field
This may seem like an easy question to some, but I am struggling with it.
I am trying to use SQLDataReader.GetFieldType to check if a specific field is an image field. Suppose 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 test this? I really don't like:
if (reader.GetFieldType(0).ToString="System.Byte[]")
Is there a better way?
Thank,
AJ
source to share
You can always shorten it a bit:
if(reader.GetFieldType(0) == typeof(byte[]));
Unfortunately there is no direct mapping of an image field in SQL Server to the .NET CLR type ... so you end up with a byte array.
You might want to add an additional check to ensure that the returned array of bytes - this image (byte-arrays are used for columns image
, binary
, varbinary
and rowversion
).
You can check the type mappings at:
source to share
It is preferable to use Type.IsAssignableFrom instead of looking at the type name.
Type fieldType = reader.GetFieldType(0);
bool isImageField = typeof(byte[]).IsAssignableFrom(fieldType);
This gives you some compile-time safety.
Note. This does not actually guarantee that the field will contain images. Any form of binary data can be stored in image
/ binary
/ fields varbinary
, so the only way to be sure if this image is actually is to read the value and try loading it as one. But you can use this to check if the field is binary.
source to share
Alternatively, you can use the SqlDataReader.GetSchemaTable method . This will return a datatable containing the schema of the result set and provide the actual datatype from the db - eg. the DataTypeName column of the returned schema table will be the actual SQL Server data type such as varchar and the ProviderSpecificDataType column will be System.Data.SqlType
eg.
DataTable dataSchema = reader.GetSchemaTable();
// dataSchema.Rows[0]["DataTypeName"] would return the sql server
// data type name for the first column in the resultset.
source to share