HowTo: Parsing a ByteArray to varbinary for SQL Server

  • Thread starter Thread starter Bob
  • Start date Start date
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
 
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?
 
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?
 
Back
Top