UPDATED BELOW
I am reading a Binary file using BinaryReader in VB.NET. The structure of each row in the file is:
"Category" = 1 byte
"Code" = 1 byte
"Text" = 60 Bytes
Dim Category As Byte
Dim Code As Byte
Dim byText() As Byte
Dim chText() As Char
Dim br As New BinaryReader(fs)
Category = br.ReadByte()
Code = br.ReadByte()
byText = br.ReadBytes(60)
chText = encASCII.GetChars(byText)
The problem is that the "Text" field has some funky characters used for padding. Mostly seems to be 0x00 null characters.
Is there any way to get rid of these 0x00 characters by some Encoding?
Otherwise, how can I do a replace on the chText array to get rid of the 0x00 characters? I am trying to serialize the resulting datatable to XML and it is failing on these non compliant characters. I am able to loop through the array, however I can not figure out how to do the replace?
UPDATE:
This is where I am at with a lot of help from guys/gals below. The first solutions works, however not as flexible as I hoped, the second one fails for one use case, however is much more generic.
Ad 1) I can solve the issue by passing the string to this subroutine
Public Function StripBad(ByVal InString As String) As String
Dim str As String = InString
Dim sb As New System.Text.StringBuilder
strNew = strNew.Replace(chBad, " ")
For Each ch As Char In str
If StrComp(ChrW(Val("&H25")), ch) >= 0 Then
ch = " "
End If
sb.Append(ch)
Next
Return sb.ToString()
End Function
Ad 2) This routine does takes out several offending characters, however fails for 0x00. This was adapted from MSDN, http://msdn.microsoft.com/en-us/library/kdcak6ye.aspx.
Public Function StripBadwithConvert(ByVal InString As String) As String
Dim unicodeString As String
unicodeString = InString
' Create two different encodings.
Dim ascii As Encoding = Encoding.ASCII
Dim [unicode] As Encoding = Encoding.UTF8
' Convert the string into a byte[].
Dim unicodeBytes As Byte() = [unicode].GetBytes(unicodeString)
Dim asciiBytes As Byte() = Encoding.Convert([unicode], ascii, unicodeBytes)
Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length) - 1) As Char
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
Dim asciiString As New String(asciiChars)
Return asciiString
End Function