0

I am trying to get a byte array from my SQL Server parameter. I get the data from SQL Server like this:

cmd.Parameters.Add("@Image1", SqlDbType.VarBinary).Size = 5000000;
cmd.Parameters["@Image1"].Direction = ParameterDirection.Output;

conn.Open();
cmd.ExecuteNonQuery();

string str = cmd.Parameters["@Image1"].Value.ToString();

I get the value System.Byte[] in string however I would need the whole byte array that I could store it as an image.

How would I do it using .Value returns an object would I convert that object to byte array?

3
  • Had you tried this: string str = cmd.Parameters["@Image1"].Value as byte[];? Commented Jun 1, 2018 at 14:59
  • The fact that you get System.Byte[] when you call the ToString method tells you the value is already of the type you expect. All you need to do is assign the type-casted value to a variable. Commented Jun 1, 2018 at 15:01
  • oh ok that makes more sense didn't really know you can convert it that easily. Ill Try it out Commented Jun 1, 2018 at 15:02

1 Answer 1

2

You might be overthinking this:

byte[] imageArray = (byte[])cmd.Parameters["@Image1"].Value;

EDIT: Casted right hand side. Thanks JuanR.

Sign up to request clarification or add additional context in comments.

4 Comments

@JuanR Can you explain why? We're already told cmd.Parameters["@Image1"].Value is of type System.Byte[]. This is for my own learning.
It's because of type checking at compile time. The compiler will tell you it cannot implicitly convert the type. The Value property is of type object. You are assigning it to a variable of type byte[]. The compiler has no way of knowing that the object is in fact of that type so it is forcing you to perform a cast for consistency.
I see thanks for the explanation. I've casted to byte[] in my answer.
+1 from me. I actually like this approach better as opposed to as byte[] since that one results is a null object if it cannot cast it, which can be misleading at runtime.

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.