-3

I have a BLOB file which Im reading from database. Following is the code:

    byte[] bytes;

    sdr.Read();

    bytes = (byte[])sdr["proposalDoc"];

But the below exception occurs:

"unable to convert from system.string to system.byte"
User2012384
  • 4,769
  • 16
  • 70
  • 106
puffles
  • 352
  • 2
  • 5
  • 23
  • 1
    you need to manually convert a string to a byte array. A question which is in regards to that is here (including answers): http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte (in your case the problem is that sdr["proposalDoc"] seemingly returns a string which you try to convert to byte array with (byte[]) thus that would be only possible as above. – Thomas Jan 28 '15 at 08:33
  • Try this http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte – eren Jan 28 '15 at 08:38
  • @eren ProposalDoc isnt a string . Its an attribute storing BLOB file in the database – puffles Jan 28 '15 at 08:58

1 Answers1

0

I wrote the following before noticing your clarification that the value returned as a string is really just a binary blob. If that's correct, than the link provided by the other commenters looks like what you need. But if the "blob" is actually a series of ASCII characters transformed to Unicode (or a stream of bytes where each byte was transformed into a word by setting the high order byte to 0), then something like the following would apply.

Assuming that the field returned by sdr["proposalDoc"] is really just an ASCII string converted to Unicode, and that all you're trying to do is reconstruct the ASCII byte string (nul-terminated), you could do something like the following. (Note, there may be more optimal ways of doing this, but this could get you started.)

// Get record field.
string tempString = sdr["proposalDoc"];

// Create byte array to hold one ASCII character per Unicode character
// in the field, plus a terminating nul.
bytes = new byte[tempString.Length + 1];

// Copy each character from the field to the byte array,
// keeping the low byte of the character.
int i = 0;
foreach (char c in tempString)
{
    bytes[i++] = (byte)c;
}

// Store the terminating nul character, assuming a
// nul-terminated ASCII string is the desired outcome.
bytes[i]=0;