0

我正在尝试制作一个程序,将文件的二进制代码写入单独的文本文件中。

当我在文本文件上使用这个程序时,它不会在新文件中写入任何内容。然后我对 .jpg 和 .mp3 文件进行了测试,该程序似乎编写了大部分二进制代码,但忽略了最后几个字节。这是我的代码:

Sub Main()
    Console.Write("Filename:  ")
    Dim Filename As String = Console.ReadLine()
    Console.Write("Extension: ")
    Dim Extension As String = Console.ReadLine()
    Console.WriteLine()

    Dim Stream_1 As FileStream = New FileStream(Filename & "." & Extension, FileMode.Open)
    Dim Stream_2 As FileStream = New FileStream(Filename & "_b.txt", FileMode.Create)

    Dim Reader_1 As BinaryReader = New BinaryReader(Stream_1)
    Dim Writer_2 As StreamWriter = New StreamWriter(Stream_2)

    Dim File_Bytes() As Byte = Reader_1.ReadBytes(Convert.ToInt32(Stream_1.Length))

    Dim Binary_String As String = ""

    'These are used to a add line break after every 8 bytes
    Dim Binary_String_Collection As String = ""
    Dim Counter As Integer

    For Each File_Byte In File_Bytes
        Counter += 1

        Binary_String = Convert.ToString(File_Byte, 2)

        For I = 1 To 8 - Binary_String.Length
            Binary_String = "0" & Binary_String
        Next

        Binary_String_Collection = Binary_String_Collection & Binary_String & " "

        If Counter = 8 Then
            Writer_2.WriteLine(Binary_String_Collection)

            Counter = 0
            Binary_String_Collection = ""
        End If
    Next

    If Binary_String_Collection <> "" Then
        Writer_2.WriteLine(Binary_String_Collection)
    End If

    Console.ReadLine()
End Sub

起初我认为我的程序没有正确读取二进制代码,所以我在它写入文件的位置添加了控制台输出。该程序显示正确的输出,所以我很困惑为什么它没有正确写入。

4

1 回答 1

2

确保关闭文件并正确处理流。

于 2012-08-05T07:44:42.537 回答