Opening and Viewing Text and Image Files

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 C# 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, a RichTextBox, 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.

  1. //section_one  
  2. using System;  
  3. using System.Drawing;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6. using System.IO;  
  7. using System.Resources;  
  8. namespace FileDisplay  
  9. {  
  10.     //windows_forms inherits from the Form class  
  11.     public class windows_forms : Form //class in System.Windows.Forms  
  12.     {  
  13.         // Container is the class in System.ComponentModel namespace  
  14.         private Container components;  
  15.         //MenuItem is the class in System.Windows.Forms namespace  
  16.         private MenuItem file;  
  17.         private MenuItem openfile;  
  18.         private MenuItem openTextfile;  
  19.         private MenuItem openImagefile;  
  20.         private MenuItem closefile;  
  21.         private MenuItem exit;  
  22.         private MenuItem help;  
  23.         private MenuItem abouthelp;  
  24.         //MainMenu is the class in System.Windows.Forms namespace  
  25.         private MainMenu mainMenu1;  
  26.         //RichTextBox, PictureBox, Panel are the classes in System.Windows.Forms namespace  
  27.         private RichTextBox fileLoadArea;  
  28.         private PictureBox pictureBox1;  
  29.         private Panel mainPanel;  
  30.         public windows_forms() //constructor  
  31.         {  
  32.             InitializeComponent();  
  33.         }  
  34.         private void InitializeComponent()  
  35.         {  
  36.             //initializing the classes  
  37.             this.mainMenu1 = new MainMenu();  
  38.             this.file = new MenuItem();  
  39.             this.openfile = new MenuItem();  
  40.             this.openTextfile = new MenuItem();  
  41.             this.openImagefile = new MenuItem();  
  42.             this.closefile = new MenuItem();  
  43.             this.exit = new MenuItem();  
  44.             this.help = new MenuItem();  
  45.             this.abouthelp = new MenuItem();  
  46.             this.fileLoadArea = new RichTextBox();  
  47.             this.pictureBox1 = new PictureBox();  
  48.             this.mainPanel = new Panel();  
  49.             this.SuspendLayout();  
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 call ResumeLayout() to display the layout. The method AddRange lets us add a number of controls to a given control rather than adding them individually.
  1. // mainMenu1  
  2. this.mainMenu1.MenuItems.AddRange(new MenuItem[]  
  3. {  
  4. this.file, this.help});  
  5. // file  
  6. this.file.Index = 0;  
  7. this.file.MenuItems.AddRange(new MenuItem[]  
  8. {  
  9. this.openfile, this.closefile, this.exit});  
  10. this.file.Text = "File";  
  11. // openfile  
  12. this.openfile.Index = 0;  
  13. this.openfile.MenuItems.AddRange(new MenuItem[]  
  14. {  
  15. this.openTextfile, this.openImagefile});  
  16. this.openfile.Text = "OpenFile";  
  17. // openTextfile  
  18. this.openTextfile.Index = 0;  
  19. this.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.
  1. this.openTextfile.Click += new System.EventHandler(this.onFileOpen);  
  2. // openImagefile  
  3. this.openImagefile.Index = 1;  
  4. this.openImagefile.Text = "&OpenImageFile...";  
  5. this.openImagefile.Click += new System.EventHandler(this.onImageOpen);  
  6. // closefile  
  7. this.closefile.Index = 1;  
  8. this.closefile.Text = "CloseFile";  
  9. this.closefile.Click += new System.EventHandler(this.onFileClose);  
  10. // exit  
  11. this.exit.Index = 2;  
  12. this.exit.Text = "exit";  
  13. this.exit.Click += new System.EventHandler(this.onWindowClose);  
  14. // help  
  15. this.help.Index = 1;  
  16. this.help.MenuItems.AddRange(new MenuItem[]  
  17. {  
  18. this.abouthelp  
  19. });  
  20. this.help.Text = "Help";  
  21. // abouthelp  
  22. this.abouthelp.Index = 0;  
  23. this.abouthelp.Text = "Learning .NET";  
  24. // fileLoadArea  
  25. this.fileLoadArea.Dock = DockStyle.Fill;  
  26. this.fileLoadArea.Name = "fileLoadArea";  
  27. this.fileLoadArea.Size = new Size(600, 400);  
  28. this.fileLoadArea.Text = "";  
  29. // pictureBox1  
  30. this.pictureBox1.Location = new Point(32, 40);  
  31. this.pictureBox1.Name = "pictureBox1";  
  32. this.pictureBox1.Size = new Size(600,400);  
  33. // mainPanel  
  34. //Control class is in System.Windows.Forms namespace  
  35. this.mainPanel.Controls.AddRange(new Control[]  
  36. {  
  37. this.fileLoadArea,  
  38. this.pictureBox1  
  39. });  
  40. this.mainPanel.Dock = DockStyle.Fill;  
  41. this.mainPanel.Name = "mainPanel";  
  42. this.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.The MainMenu 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.
  1. // windows_forms  
  2. this.ClientSize = new System.Drawing.Size(600, 500);  
  3. this.Controls.AddRange(new Control[]  
  4. {  
  5. this.mainPanel  
  6. });  
  7. this.Menu = this.mainMenu1;  
  8. this.Name = "windows_forms";  
  9. this.Text = "Learning Windows Forms";  
  10. mainPanel.Hide();  
  11. this.ResumeLayout();  
  12. }  
  13. //section_one:end  
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 like InitialDirectory 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.
  1. //section_two  
  2. //Handler for the TextFileOpen command  
  3. private void onFileOpen(object sender, EventArgs e)  
  4. {  
  5.     if (pictureBox1 != null)  
  6.         pictureBox1.Hide();  
  7.     fileLoadArea.Text = "";  
  8.     mainPanel.Show();  
  9.     fileLoadArea.Show();  
  10.     OpenFileDialog openFileDialog1 = new OpenFileDialog();  
  11.     openFileDialog1.InitialDirectory = "d:\\";  
  12.     openFileDialog1.RestoreDirectory = true;  
  13.     openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Rich Text Format (*.rtf)|*.rtf)|" + " All Files (*.*)|*.*";  
  14.     if (openFileDialog1.ShowDialog() == DialogResult.OK)  
  15.     {  
  16.         String fileName = openFileDialog1.FileName;  
  17.         if (fileName.Length != 0)  
  18.         {  
  19.             try  
  20.             {  
  21.                 ReadFileInfo(fileName);  
  22.             }  
  23.             catch  
  24.             {  
  25.                 MessageBox.Show(String.Format("{0} is not " + "a valid image file", fileName), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  26.             }  
  27.         }  
  28.     }  
  29. }  
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 FileInfo class provides the instance methods for the opening, moving etc of the files. The Extension property 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.
  1. private void ReadFileInfo(String filename)  
  2. {  
  3.     try  
  4.     {  
  5.         FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);  
  6.         FileInfo fInfo = new FileInfo(filename);  
  7.         string fext = fInfo.Extension.ToUpper();  
  8.         if (fext.Equals(".RTF"))  
  9.             fileLoadArea.LoadFile(fs, RichTextBoxStreamType.RichText);  
  10.         else  
  11.             fileLoadArea.LoadFile(fs, RichTextBoxStreamType.PlainText);  
  12.         fs.Close();  
  13.     }  
  14.     catch (Exception e)  
  15.     {  
  16.         Console.WriteLine("Exception" + e.StackTrace);  
  17.     }  
  18. }  
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.
  1. // Handler for the ImageFileOpen command  
  2. private void onImageOpen(object sender, EventArgs e)  
  3. {  
  4.     if (fileLoadArea != null)  
  5.     {  
  6.         fileLoadArea.Hide();  
  7.     }  
  8.     mainPanel.Show();  
  9.     OpenFileDialog ofd = new OpenFileDialog();  
  10.     ofd.Filter = "Image Files (*.bmp)|*.bmp|JPEG Files (*.jpeg)|*.jpeg|" + " All Files (*.*)|*.*";  
  11.     if (ofd.ShowDialog() == DialogResult.OK)  
  12.     {  
  13.         String fileName = ofd.FileName;  
  14.         if (fileName.Length != 0)  
  15.         {  
  16.             try  
  17.             {  
  18.                 pictureBox1.BackgroundImage = new Bitmap(fileName);  
  19.                 pictureBox1.Show();  
  20.             }  
  21.             catch  
  22.             {  
  23.                 MessageBox.Show(String.Format("{0} is not " + "a valid image file", fileName), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  24.             }  
  25.         }  
  26.     }  
  27. }  
  28. // method to drive the File/Close button  
  29. private void onFileClose(object sender, System.EventArgs e)  
  30. {  
  31.     mainPanel.Hide();  
  32. }  
  33. // method to drive the Window/Close button  
  34. private void onWindowClose(object sender, System.EventArgs e)  
  35. {  
  36.     // Handler for the Close command  
  37.     Close();  
  38. }  
  39. public static void Main(string[] args)  
  40. {  
  41.     Application.Run(new windows_forms());  
  42. }  
  43. protected override void Dispose(bool disposing)  
  44. {  
  45.     if (disposing)  
  46.     {  
  47.         if (components != null)  
  48.         {  
  49.             components.Dispose();  
  50.         }  
  51.     }  
  52.     base.Dispose(disposing);  
  53. }  
  54. }  
  55. }  
  56. //Section two end  
Conclusion
 
Hope this application proved useful to you and gave you an insight of working with the OpenFileDialog classes.

Viewing a text file

TextImgViewerMMImg1.jpg

Viewing an Image

TextImgViewerMMImg2.jpg


Similar Articles