Dump Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Dump


Objetive:

Create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should pause after displaying each screen before displaying the next 24 rows.

In each row, the 16 bytes must be displayed first in hexadecimal format and then as characters. Bytes with ASCII code less than 32 must be displayed as a dot instead of the corresponding non-printable character.

You can look for "hex editor" on Google Images to see an example of the expected appearance.


Code:

Imports System
Imports System.IO
Public Class Dump
    Public Shared Sub Main()
        Dim file As FileStream
        Const SIZE_BUFFER As Integer = 16
        Dim name As String = Console.ReadLine()

        Try
            file = File.OpenRead(name)
            Dim data As Byte() = New Byte(15) {}
            Dim amount As Integer
            Dim c As Integer = 0
            Dim line As String

            Do
                Console.Write(ToHex(file.Position, 8))
                Console.Write("  ")
                amount = file.Read(data, 0, SIZE_BUFFER)

                For i As Integer = 0 To amount - 1
                    Console.Write(ToHex(data(i), 2) & " ")

                    If data(i) < 32 Then
                        line += "."
                    Else
                        line += Convert.ToChar(data(i))
                    End If
                Next

                If amount < SIZE_BUFFER Then

                    For i As Integer = amount To SIZE_BUFFER - 1
                        Console.Write("   ")
                    Next
                End If

                Console.WriteLine(line)
                line = ""
                c += 1

                If c = 24 Then
                    Console.ReadLine()
                    c = 0
                End If
            Loop While amount = SIZE_BUFFER

            file.Close()
        Catch __unusedException1__ As Exception
            Console.WriteLine("Error")
        End Try
    End Sub

    Public Shared Function ToHex(ByVal n As Integer, ByVal digits As Integer) As String
        Dim hex As String = Convert.ToString(n, 16)

        While hex.Length < digits
            hex = "0" & hex
        End While

        Return hex
    End Function
End Class

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