0

I have

0x4D5A90000300000004000000FFFF0000B80000000000000040...

generated from sql server.

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

6
  • 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 ? Commented Dec 19, 2016 at 12:02
  • we are writing custom tool for default data management. Commented Dec 19, 2016 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. Commented Dec 19, 2016 at 12:08
  • we are storing byte string in excel to import using entity framework. Commented Dec 19, 2016 at 12:15
  • Yet you mention sql server repeatedly and Excel never... you can see why this would be confusing, I hope Commented Dec 19, 2016 at 12:25

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.