문제

아래에서 업데이트되었습니다

vb.net에서 BinaryReader를 사용하여 이진 파일을 읽고 있습니다. 파일의 각 행의 구조는 다음과 같습니다.

    "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)

문제는 "텍스트"필드에 패딩에 사용되는 펑키 캐릭터가 있다는 것입니다. 대부분 0x00 null 문자 인 것 같습니다.

  1. 인코딩 으로이 0x00 문자를 제거하는 방법이 있습니까?

  2. 그렇지 않으면 0x00 문자를 제거하기 위해 Chtext 배열에서 어떻게 교체 할 수 있습니까? 결과 데이터 가능을 XML로 직렬화하려고 노력하고 있으며 이러한 호환되지 않은 문자에서는 실패합니다. 배열을 통해 반복 할 수 있지만 교체 방법을 알 수 없습니까?

업데이트:

이곳은 내가 아래의 남자/여자들로부터 많은 도움을 받고있는 곳입니다. 첫 번째 솔루션은 내가 기대했던 것만 큼 유연하지는 않지만 두 번째 솔루션은 하나의 유스 케이스에 실패하지만 훨씬 일반적입니다.

AD 1)이 서브 루틴에 문자열을 전달하여 문제를 해결할 수 있습니다.

    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)이 루틴은 몇 가지 불쾌한 문자를 제거하지만 0x00에는 실패합니다. 이것은 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
도움이 되었습니까?

해결책

우선 텍스트의 형식이 무엇인지 알아 내야하므로 쳤던 것을 알지 못하고 무언가를 맹목적으로 제거하고 있습니다.

형식에 따라 다른 방법을 사용하여 문자를 제거합니다.

제로 문자 만 제거하려면 :

Dim len As Integer = 0
For pos As Integer = 0 To byText.Length - 1
   If byText(pos) <> 0 Then
      byText(len) = byText(pos)
      len += 1
   End If
Next
strText = Encoding.ASCII.GetChars(byText, 0, len)

첫 번째 제로 문자에서 배열 끝까지 모든 것을 제거하려면 :

Dim len As Integer
While len < byText.Length AndAlso byText(len) <> 0
   len += 1
End While
strText = Encoding.ASCII.GetChars(byText, 0, len)

편집하다:
ASCII 캐릭터 인 정크를 유지하려면 다음과 같습니다.

Dim len As Integer = 0
For pos As Integer = 0 To byText.Length - 1
   If byText(pos) >= 32 And byText(pos) <= 127 Then
      byText(len) = byText(pos)
      len += 1
   End If
Next
strText = Encoding.ASCII.GetChars(byText, 0, len)

다른 팁

널 문자가 오른쪽 패딩으로 사용되는 경우 (예 : 종료) 정상적인 경우 인 텍스트는 매우 쉽습니다.

Dim strText As String = encASCII.GetString(byText)
Dim strlen As Integer = strText.IndexOf(Chr(0))
If strlen <> -1 Then
    strText = strText.Substr(0, strlen - 1)
End If

그렇지 않다면 여전히 정상을 할 수 있습니다 Replace 문자열에. 바이트 어레이에서 가지 치기를했다면 약간 "클리너"가 될 것입니다. ~ 전에 문자열로 변환합니다. 그러나 원칙은 동일하게 유지됩니다.

Dim strlen As Integer = Array.IndexOf(byText, 0)
If strlen = -1 Then
    strlen = byText.Length + 1
End If
Dim strText = encASCII.GetString(byText, 0, strlen - 1)

구조물을 사용하여 데이터를로드 할 수 있습니다.

[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
internal struct TextFileRecord
{
    [System.Runtime.InteropServices.FieldOffset(0)]
    public byte Category;
    [System.Runtime.InteropServices.FieldOffset( 1 )]
    public byte Code;
    [System.Runtime.InteropServices.FieldOffset( 2 )]
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr, SizeConst=60)]
    public string Text;
}

문자열 인코딩에 맞도록 관리되지 않은 유형의 관점을 조정해야합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top