Dump Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Dump 86


Objetive:

Create a "dump" utility: an hex viewer, to display the contents of a file, 16 bytes in each row, 24 files in each screen (and then it must pause before displaying the next 24 rows).

In each row, the 16 bytes must be displayed first in Hex and then as characters (the bytes under 32 must be displayed as a dot, instead of the corresponding non printable character).

Look for "hex editor" in Google Images, if you want to see and 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