Extract text from a binary file Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Extract text from a binary file


Objetive:

Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters should be those whose ASCII code is between 32 and 127, or equal to 10 or 13.


Code:

Imports System
Imports System.IO
Class FileBinay
    Private Shared Sub Main()
        Dim file As FileStream
        Dim name As String
        Console.WriteLine("Enter the file name: ")
        name = Console.ReadLine()

        If Not File.Exists(name) Then
            Console.WriteLine("File {0} not found!", name)
        Else

            Try
                file = File.OpenRead(name)
                Dim bytesFile As Byte() = New Byte(file.Length - 1) {}
                file.Read(bytesFile, 0, CInt(file.Length))
                file.Close()
                Dim newFile As StreamWriter = New StreamWriter(name & "01.txt")

                For i As Integer = 0 To bytesFile.Length - 1

                    If (Convert.ToInt32(bytesFile(i)) >= 32) AndAlso (Convert.ToInt32(bytesFile(i)) <= 127) OrElse (Convert.ToInt32(bytesFile(i)) = 10) OrElse (Convert.ToInt32(bytesFile(i)) = 13) Then
                        newFile.Write(Convert.ToChar(bytesFile(i)))
                    End If
                Next

                newFile.Close()
            Catch e As Exception
                Console.WriteLine("Error, " & e.Message)
            End Try
        End If
    End Sub
End Class

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.