Opening and Viewing Images and Text Files in VB.NET

We will start this article with a simple application where we will learn how to open and view text and image files using the OpenFileDialog class. In doing so, we will learn some basics of GDI+ drawing, menus and panel control. I assume you have some familiarity with the .NET framework and how to develop Windows applications using VB.NET and hence I am not delving into the basics of these topics.

The application that I am going to explain has two menu options: File and Help. File has three sub-menu options: Openfile, Closefile and exit Openfile option allows you to open either a text file or an image file. Help has a dummy sub-option Learning .NET, which I leave upon the readers to attach events and play around with. I will explain every option in more details as we explore the code. In section_ one of the code, I will define and initialize the different classes to draw Menus, aRichTextBox, a PictureBox and a Panel. A Panel is a control that contains other controls. It holds the two controls: RichTextBox and PictureBox in this case. A RichTextBox control allows you to load a Rich Text Format (RTF) or a plain text file and do editing on it. A PictureBox control is used to display graphics from GIF, JPEG or bitmaps etc.

Imports System 
Imports System.Drawing
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.IO
Imports System.Resources
Namespace FileDisplay
'windows_forms inherits from the Form class
Public Class windows_forms
Inherits Form 'class in System.Windows.Forms 
' Container is the class in System.ComponentModel namespace
Private components As Container
'MenuItem is the class in System.Windows.Forms namespace
Private file As MenuItem
Private openfile As MenuItem
Private openTextfile As MenuItem
Private openImagefile As MenuItem
Private closefile As MenuItem
Private [exit] As MenuItem
Private help As MenuItem
Private abouthelp As MenuItem
'MainMenu is the class in System.Windows.Forms namespace
Private mainMenu1 As MainMenu
'RichTextBox, PictureBox, Panel are the classes in System.Windows.Forms namespace
Private fileLoadArea As RichTextBox
Private pictureBox1 As PictureBox
Private mainPanel As Panel
Public Sub New() 'constructor
End Sub 
Private Sub InitializeComponent()
'initializing the classes
Me.mainMenu1 = New MainMenu
Me.file = New MenuItem
Me.openfile = New MenuItem
Me.openTextfile = New MenuItem
Me.openImagefile = New MenuItem
Me.closefile = New MenuItem
Me.exit = New MenuItem = New MenuItem
Me.abouthelp = New MenuItem
Me.fileLoadArea = New RichTextBox
Me.pictureBox1 = New PictureBox
Me.mainPanel = New Panel
End Sub 'InitializeComponent
End Class 'windows_forms
End Namespace 'FileDisplay

SuspendLayout() method temporarily suspends the layout logic of the controls. You can set the properties of the control like Name, Text, Size, Dock (as has been done) and then callResumeLayout() to display the layout. The method AddRange lets us add a number of controls to a given control rather than adding them individually.

' mainMenu1
Me.mainMenu1.MenuItems.AddRange(New MenuItem() {Me.file,})
' file
Me.file.Index = 0
Me.file.MenuItems.AddRange(New MenuItem() {Me.openfile, Me.closefile, Me.exit})
.file.Text = "File"
' openfile
Me.openfile.Index = 0
Me.openfile.MenuItems.AddRange(New MenuItem() {Me.openTextfile, Me.openImagefile})
Me.openfile.Text = "OpenFile"
' openTextfile
Me.openTextfile.Index = 0
Me.openTextfile.Text = "OpenTextFile..."

Whenever the user clicks on the sub-menu option 'OpenTextFile...' we attach an event handler called 'onFileOpen' to handle the clicks. What this event handler does will soon become clear. The same follows when the user clicks 'OpenImageFile...' option. Its event handler gets triggered to handle the event and so on for the menu-options 'CloseFile' and 'exit'.

Me.openTextfile.Click += New System.EventHandler(Me.onFileOpen)
' openImagefile
Me.openImagefile.Index = 1
Me.openImagefile.Text = "&OpenImageFile..."
Me.openImagefile.Click += New System.EventHandler(Me.onImageOpen)
' closefile
Me.closefile.Index = 1
Me.closefile.Text = "CloseFile"
Me.closefile.Click += New System.EventHandler(Me.onFileClose)
' exit
Me.exit.Index = 2
Me.exit.Text = "exit"
Me.exit.Click += New System.EventHandler(Me.onWindowClose)
' help = 1 MenuItem() {Me.abouthelp}) = "Help"
' abouthelp
Me.abouthelp.Index = 0
Me.abouthelp.Text = "Learning .NET"
' fileLoadArea
Me.fileLoadArea.Dock = DockStyle.Fill
Me.fileLoadArea.Name = "fileLoadArea"
Me.fileLoadArea.Size = New Size(600, 400)
Me.fileLoadArea.Text = ""
' pictureBox1
Me.pictureBox1.Location = New Point(32, 40)
Me.pictureBox1.Name = "pictureBox1"
Me.pictureBox1.Size = New Size(600, 400)
' mainPanel
'Control class is in System.Windows.Forms namespace
Me.mainPanel.Controls.AddRange(New Control() {Me.fileLoadArea,Me.pictureBox1})Me.mainPanel.Dock = DockStyle.Fill
Me.mainPanel.Name = "mainPanel"
Me.mainPanel.Size = New Size(600, 400)

The different properties of the form window is shown below: ClientSize property determines the size of the form area where controls can be placed.The form itself contains the main panel.TheMainMenu is assigned to the form using the Menu property of the form.The Text property sets the caption of the form.Finally a call is given to ResumeLayout() method to display the layout.Before the layout is displayed we are hiding the mainPanel as we do not want it to show itself when the form is initialized and displayed.

' windows_forms
Me.ClientSize = New System.Drawing.Size(600, 500)
Me.Controls.AddRange(New Control() {Me.mainPanel})
Me.Menu = Me.mainMenu1
Me.Name = "windows_forms"
Me.Text = "Learning Windows Forms"

In section_two I will show how to open a text file or an image file based on the event fired.

The 'onFileOpen' event handler opens a text file (plain text or Rich Text files) based on the option selected. It hides the PictureBox control and shows the RichTextBox control where the file is loaded.

An instance of the OpenFileDialog class (present in System.Windows.Forms namespace) presents a dialog box to assist you in opening a file. It has a number of methods and properties likeInitialDirectory to set the directory to start with and RestoreDirectory (when true) restores the directory to the same initial directory, if the user has modified it while searching for the files and Filter which takes a string and determines the choices that appears when the dialog box is displayed. If then extracts the filename and calls ReadFileInfo() method with the filename. 

'section_two//Handler for the TextFileOpen command
Private Sub onFileOpen(ByVal sender As Object, ByVal e As EventArgs)
If Not (pictureBox1 Is Nothing) Then
End If
fileLoadArea.Text = ""
Dim openFileDialog1 As New OpenFileDialog
openFileDialog1.InitialDirectory = "d:\"
openFileDialog1.RestoreDirectory = 
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Rich Text Format (*.rtf)|*.rtf)|" +  All Files (*.*)|*.*"
If openFileDialog1.ShowDialog() = DialogResult.OK Then
 fileName As [String] = openFileDialog1.FileName
If fileName.Length <> 0 Then
End Try
 Sub 'onFileOpen

The ReadFileInfo () method takes the string name as a parameter, opens a FileStream object and reads the file. The FileStream and FileInfo classes are seen in System.IO namespace. The FileInfoclass provides the instance methods for the opening, moving etc of the files. The Extensionproperty returns the extension part of the filename.

Depending on whether the file is RTF or plain, RichTextBox control calls its method LoadFile to load the file.

Private Sub ReadFileInfo(ByVal filename As [String])
Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim fInfo As New FileInfo(filename)
Dim fext As String = fInfo.Extension.ToUpper()
If fext.Equals(".RTF") Then
fileLoadArea.LoadFile(fs, RichTextBoxStreamType.RichText)
fileLoadArea.LoadFile(fs, RichTextBoxStreamType.PlainText)
End If
Catch e As Exception
Console.WriteLine(("Exception" + e.StackTrace))
 Sub 'ReadFileInfo

The 'onImageOpen' event handler opens an image file. It hides the RichTextBox control.

In this case, it takes as its filter string a set of image file extensions. The Bitmap constructor of the Bitmap class (in System.Drawing namespace) converts the string filename to a bitmap and stores the image in the BackgroundImage property of PictureBox control. It then calls the Show() method of PictureBox control to show the image.

' Handler for the ImageFileOpen command
Private Sub onImageOpen(ByVal sender As Object, ByVal e As EventArgs)
If Not (fileLoadArea Is Nothing) Then
End If
Dim ofd As New OpenFileDialog
ofd.Filter = "Image Files (*.bmp)|*.bmp|JPEG Files (*.jpeg)|*.jpeg|" + " All Files (*.*)|*.*"
If ofd.ShowDialog() = DialogResult.OK Then
 fileName As [String] = ofd.FileName
If fileName.Length <> 0 Then
pictureBox1.BackgroundImage = New Bitmap(fileName)
End Try
 Sub 'onImageOpen
' method to drive the File/Close button
Private Sub onFileClose(ByVal sender As Object, ByVal e As System.EventArgs)mainPanel.Hide()
End Sub 'onFileClose
' method to drive the Window/Close button
Private Sub onWindowClose(ByVal sender As Object, ByVal e As System.EventArgs)
' Handler for the Close command
End Sub 'onWindowClose
'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
End Sub
 Overloads Shared Sub Main(ByVal args() As String)
Application.Run(New windows_forms)
End Sub 'Main
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
 Not (components Is Nothing) Then
End If
End Sub 'Dispose
'Section two end

Conclusion: Hope this application proved useful to you and gave you an insight of working with theOpenFileDialog classes.

Screen Shots

Viewing a text file

Viewing an Image