devxlogo

A cheap way to display files and hex data

A cheap way to display files and hex data

The .NET framework includes a ByteViewer control, that you can use on your own forms to display data stored in a Byte array or in a file. The ByteViewer control can’t be added to the control Toolbox, though, so you must instantiate it through code only.

' IMPORTANT: this code requires a reference to the System.Design.Dll assemblyDim WithEvents bv As New ByteViewer()Private Sub Form1_Load(ByVal sender As System.Object, _    ByVal e As System.EventArgs) Handles MyBase.Load    ' the ByteViewer control has a fixed width    ' only the height value is used    bv.Size = New Size(10, 100)    bv.ForeColor = Color.Blue    ' the background color doesn't affect the area where    ' text or hex values are displayed    bv.BackColor = Color.LightGray    ' make it visible and display on the parent form    bv.Visible = True    Me.Controls.Add(bv)    ' display the autoexec.bat file in both text and hex mode    bv.SetFile("c:autoexec.bat")    bv.SetDisplayMode(DisplayMode.Ansi)End Sub

The SetDisplayMode method can take one of the following values: Ansi, Unicode, Hexdump, and Auto. In auto mode the control attempts to determine the display mode automatically.

The DisplayMode.Hexdump value is very useful, in that the control displays both hex values and text. This is especially useful when used with the SetBytes method, that takes a Byte array as an argument:

' read a file into a Byte arrayDim sr As New System.IO.FileStream("c:inary.dat", IO.FileMode.Open)Dim bytes(sr.Length - 1) As Bytesr.Read(bytes, 0, sr.Length)sr.Close()' display in the controlbv.SetBytes(bytes)

Notice that the ByteViewer class inherits from Control and therefore it exposes all the usual properties, methods, and events. However, a few properties don’t work as usual. For example, the Width property is ignored and the control is always 633 pixels wide.

devx-admin

Share the Post: