tags:

views:

184

answers:

1

how to get varchar as byte[] data using DataReader in Ado.Net? We have tried the following code.

if (!objDataReader.IsDBNull(i))
                  {
                                long len = objDataReader.GetBytes(i, 0, null, 0, 0);

                                byte[] buffer = new byte[len];
                                objDataReader.GetBytes(i, 0, buffer, 0, (int)len);

                  }

But the above code gives the error ("Unable to cast object of type 'System.String' to type 'System.Byte[]'.")

Update:

When value for a column is null and i remove dbnull condition then executing following lines of code gives an error as "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]"

long len = objDataReader.GetBytes(i, 0, null, 0, 0);
byte[] buffer = new byte[len];
objDataReader.GetBytes(i, 0, buffer, 0, (int)len);
+4  A: 

A varchar field should be storing text, not raw bytes. If you want to store opaque binary data, use image or binary.

If you want to get the bytes which represent some text in a particular encoding, you can use Encoding.GetBytes - but you'll need to specify the encoding, e.g. Encoding.UTF8.GetBytes(text). However, that may not be how it's represented in the database. The point is that it's text data, so the exact binary representation shouldn't matter, so long as you can accurately reproduce the Unicode string.

What are you storing in this field?

Jon Skeet
code works when i don't check for dbnull but gives an error when value is return is null and error message is as "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'".
Krishna
@Krishna: If the value is null, then your test (in the first line you posted) should stop you from going into the block. Could you post your changed code?
Jon Skeet
@Jon : Please have look at my update in post.
Krishna
@Krishna: Why have you removed the null condition? That was obviously avoiding that part of the problem - so put it back in.
Jon Skeet
@Jon : if i put it back i will get other error of 'System.String' to type 'System.Byte[]'.
Krishna
@Krishna: Yes, because you've ignored my answer. You'd still get that problem for non-null values anyway - you've just made null values fail *as well*.
Jon Skeet