views:

32

answers:

1

I have taken over support of an application at the company I work for. All of a sudden, the customer wants to be able to enter a registered trademark in a name field. The symbol, using ALT+0174, is being saved correctly, but the app is not encoding it properly. Essentially this is what I'm doing:

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Dim ms As New MemoryStream
    Dim xml_text_writer As New XmlTextWriter(ms, _
        System.Text.Encoding.UTF8)

    xml_text_writer.Formatting = Formatting.Indented
    xml_text_writer.Indentation = 4

    xml_text_writer.WriteStartDocument(True)
    xml_text_writer.WriteStartElement("Employees")

    MakeEmployee(xml_text_writer, txtFName.Text, txtLName.Text, 11111)

    xml_text_writer.WriteEndElement()
    xml_text_writer.WriteEndDocument()
    xml_text_writer.Flush()

    ms.Flush()
    ms.Position = 0
    Dim b(CInt(ms.Length) - 1) As Byte
    ms.Read(b, 0, CInt(ms.Length))
    ms.Close()

    Dim strReturn As String = System.Text.ASCIIEncoding.ASCII.GetString(b)
    If strReturn.StartsWith("???", StringComparison.CurrentCultureIgnoreCase) Then
        strReturn = strReturn.Substring(3)
    End If

    txtName.Text = strReturn

End Sub

Private Sub MakeEmployee(ByVal xml_text_writer As  _
XmlTextWriter, ByVal first_name As String, ByVal _
last_name As String, ByVal emp_id As Integer)
    xml_text_writer.WriteStartElement("Employee")

    xml_text_writer.WriteStartElement("FirstName")
    xml_text_writer.WriteString(first_name)
    xml_text_writer.WriteEndElement()

    xml_text_writer.WriteStartElement("LastName")
    xml_text_writer.WriteString(last_name)
    xml_text_writer.WriteEndElement()

    xml_text_writer.WriteStartElement("EmployeeId")
    xml_text_writer.WriteString(emp_id.ToString)
    xml_text_writer.WriteEndElement()

    xml_text_writer.WriteEndElement()
End Sub

The output I get from this code is this:

John Smith ?? 11111

Everything is fine, except the "??" after "Smith" should be "®". What is the best way, if any, to display the symbol correctly?

+2  A: 

Dim strReturn As String = System.Text.ASCIIEncoding.ASCII.GetString(b)

You encoded the XML in UTF-8, don't read it back as ASCII. You'll lose all the special characters that cannot be encoded. Fix:

Dim strReturn As String = System.Text.Encoding.UTF8.GetString(b)
Hans Passant
Wow...it's just that easy! Thank you very much...that worked!
LDWisdom