Casting SqlParameter/Object as a Byte array

2 03 2010

I’ve just spent ages working this out, and all the time I was just making a silly mistake! So hopefully this may save someone else the pain! For anyone that doesn’t want to read the rest of the post, the code to do it is:

byte[] fileContents = (byte[])sqlParameters[3].Value;

I was saving a PDF file as a byte array and then inserting that to my database as a varbinary. I needed to be able to then get that varbinary back out of the database as a byte array, and open it without corrupting the information.

So casting is the obvious candidate. But I made a silly mistake and had the following:

byte[] fileContents = (byte)sqlParamters[3].Value;

Which caused a problem as I was trying to cast a single byte to a byte array. I then got all caught up in using the ToString() method on the parameter value and then converting it from a string to a byte array. It just kept getting corrupted!

When I actually sat back and thought about it, a SqlParameter is just an object. So a simple cast is all that’s required. When I took a step back, I realised my code should have been:

byte[] fileContents = (byte[])sqlParameters[3].Value;

See what I mean about it being a stupid mistake?! All I needed was the square brackets in the casting and now it works perfectly, giving me back my lovely PDF, uncorrupted!

Sometime problems aren’t as complicated as you first think and the easy solution is the right one 🙂

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: