I was facing a problem where I got data (String) from a database with Linebreaks as (Hex) 0D
. I displayed this data in a Textbox
, which did not use the 0D
as a linbreak. I found that the Textbox needs 0D-0A
(LF & CR, dont know which is which) to actually show the new line. To solve this problem I came up with the following code.
Private Function convertString(txt As String) As String
Dim data = System.Text.Encoding.Default.GetBytes(txt)
Dim hexString As String = BitConverter.ToString(data)
hexString = hexString.Replace("0D", "0D-0A")
Dim arr As [String]() = hexString.Split("-"c)
Dim array As Byte() = New Byte(arr.Length - 1) {}
For i As Integer = 0 To arr.Length - 1
array(i) = Convert.ToByte(arr(i), 16)
Next
Return System.Text.Encoding.Default.GetString(array)
End Function
Explanation/procedure:
1. Convert String to ByteArray
2. Convert ByteArray to Hex-String (Hex-Chars separated by '-' )
3. Adding the missing lf or cr by replacing the solo one
4. Convert Hex-String back to ByteArray
5. Convert ByteArray back to String
Now my question:
I am pretty sure there is a better way to do that. How can I simplify those lines of code?