0

I have

0x4D5A90000300000004000000FFFF0000B80000000000000040...

generated from sql server.

How can I insert byte string into byte[] column in database using EntityFramework?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Ravi
  • 398
  • 3
  • 11
  • 1
    Are you *sure* you have it as a string? I would expect SQL Server to return that as a byte[], but most tools will *represent* it as a string in the form `0x{hex}`. Is there any reason you can't have SQL Server just return the `varbinary` ? – Marc Gravell Dec 19 '16 at 12:02
  • we are writing custom tool for default data management. – Ravi Dec 19 '16 at 12:06
  • @Ravinda that doesn't tell me why you are representing binary data as text... there should be no need to do that. A `varbinary(max)` to store the binary should be fine. – Marc Gravell Dec 19 '16 at 12:08
  • we are storing byte string in excel to import using entity framework. – Ravi Dec 19 '16 at 12:15
  • Yet you mention sql server repeatedly and Excel never... you can see why this would be confusing, I hope – Marc Gravell Dec 19 '16 at 12:25
  • Possible duplicate of http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa – ErikEJ Dec 19 '16 at 12:25

1 Answers1

2

As per my comment above, I strongly suspect that the best thing to do here is to return the data as a byte[] from the server; this should be fine and easy to do. However, if you have to use a string, then you'll need to parse it out - take off the 0x prefix, divide the length by 2 to get the number of bytes, then loop and parse each 2-character substring using Convert.ToByte(s, 16) in turn. Something like (completely untested):

int len = (value.Length / 2)-1;
var arr = new byte[len];
for(int i = 0; i < len;i++) {
    var s = value.Substring((i + 1) * 2, 2);
    arr[i] = Convert.ToByte(s, 16);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900