Dump Learn programming C#



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:

using System;
using System.IO;
public class Dump
{
    public static void Main()
    {
        FileStream file;
        const int SIZE_BUFFER = 16;

        string name = Console.ReadLine();

        try
        {
            file = File.OpenRead(name);
            byte[] data = new byte[SIZE_BUFFER];

            int amount;
            int c = 0;

            string line;
            do
            {
                Console.Write(ToHex(file.Position, 8));
                Console.Write("  ");


                amount = file.Read(data, 0, SIZE_BUFFER);

                for (int i = 0; i < amount; i++)
                {
                    Console.Write(ToHex(data[i], 2) + " ");

                    if (data[i] < 32)
                        line += ".";
                    else
                        line += Convert.ToChar(data[i]);
                }


                if (amount < SIZE_BUFFER)
                {
                    for (int i = amount; i < SIZE_BUFFER; i++)
                    {
                        Console.Write("   ");
                    }
                }

                Console.WriteLine(line);
                line = "";

                c++;
                if (c == 24)
                {
                    Console.ReadLine();
                    c = 0;
                }
            }
            while (amount == SIZE_BUFFER);

            file.Close();
        }
        catch (Exception)
        {
            Console.WriteLine("Error");
        }
    }

    public static string ToHex(int n, int digits)
    {
        string hex = Convert.ToString(n, 16);
        while (hex.Length < digits)
            hex = "0" + hex;
        return hex;
    }
}



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