1110
1110

Reputation: 6839

How to store byte[] in text field in database and retrieve it

I have a large issue.
I uploaded image and get byte[].
In database I have NVARCHAR(MAX) field and it can't be changed.
What ever I do and save in database I can't get it as image later.
I triedn .ToString() doesn't work.
I have tried this:

private byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

And when I try to put it in RadBinaryImage I get nothing.
This is the error:

 The provided binary data may not be valid image or may contains unknown header

Upvotes: 3

Views: 8151

Answers (1)

Kendrick
Kendrick

Reputation: 3787

You probably want to encode it, rather than just convert directly.

I've successfully used Radix-64 encoding in the past. There's a C# method for it, but I haven't used it:

Convert.ToBase64String(byteArrayForImage);

http://msdn.microsoft.com/en-us/library/dhx0d524.aspx

Then you can use the reverse conversion to get your byte array:

Convert.FromBase64String(stringFromDB)

Upvotes: 10

Related Questions