HowTo: Parsing a ByteArray to varbinary for SQL Server

B

Bob

I thought this was pretty cool, so I'm going to post it just in case anyone
wanted to know.

This is for when you need to use a varbinary type in SQL you're building by
hand. Use the value returned below without quotes.

Bob

Public Function GetVarbinaryStringFromByteArray(ByVal Bytes() As
Byte) As String
Dim ret As String
If Bytes Is Nothing OrElse Bytes.GetUpperBound(0) < 0 Then
ret = "NULL"
Else
Dim strb As New System.Text.StringBuilder("0x")
For Each b As Byte In Bytes
Dim h As String = Hex(b)
If h.Length = 1 Then h = "0" & h
strb.Append(h)
Next
ret = strb.ToString
End If
Return ret
End Function
 
J

Jon Skeet [C# MVP]

Bob said:
I thought this was pretty cool, so I'm going to post it just in case anyone
wanted to know.

This is for when you need to use a varbinary type in SQL you're building by
hand. Use the value returned below without quotes.

Any reason not to use BitConverter.ToString(byte[]) and munge that into
a different format if you particularly want to?
 
B

Bob

Thank you for the tip, I'm glad I posted.
Bob.ClueCollection.Add(New Clue(GetType(BitConverter)))

Bob

Jon Skeet said:
Bob said:
I thought this was pretty cool, so I'm going to post it just in case anyone
wanted to know.

This is for when you need to use a varbinary type in SQL you're building by
hand. Use the value returned below without quotes.

Any reason not to use BitConverter.ToString(byte[]) and munge that into
a different format if you particularly want to?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top