Reader Level:
ARTICLE

File Reader & Writer and File Open Dialog & Folder Open Dialog in C# - Part 1

Posted by Sivaraman Dhamodaran Articles | Windows Forms C# January 06, 2011
First part of this article explains the usage of the File Open dialog and Stream Reader class. In the next part we will see how to use the Folder Open dialog and Stream Writer.
  • 0
  • 0
  • 11066
Download Files:
 

1. Introduction

Here you will see how to use the File Open dialog and folder select dialogs. Also you will see how to use the StreamReader and StreamWriter classes. We will also use the Path utility class, which has a static function to phrase the string that comes in the form of file path.

Before we start, have a look at the picture below which was taken when the form is running:

Pic01.JPG

How it Works

When you click the button, a file open dialog is displayed asking you to select Bmp or Jpg image file or a text file. If you select a file other than the above-specified three formats, an error will be displayed and file open dialog still stays to select a different file. When a text file is selected it will be displayed in the top portion of the dialog. This is shown in the above screen shot. When you select a bmp or jpg file the selected image is displayed instead of the text.

The Save File button will save whatever text content is displayed in the multiple line textbox. It takes the file name from the Save File Name textbox and saves that in the text format. Before saving, it will ask you to select folder by displaying the Folder Select dialog. Once the file is saved, the saved location is shown below in a label. Save in Temp Path saves the file in the system temporary path. 

OK. Let us start developing it.

2. Design the Form

Start a Visual C# Windows application. Then design the form by taking the guidance from the previous section. From the downloaded solution (Visual studio 2005) have a look at each control's properties changed from the default (The bold values in the property window).

The following is the short guidance:

The OpenFileDialog and FolderBrowser dialogs are available under the dialogs group in your toolbox. Drag and drop those controls to the form. And these controls are then shown below the form after you dropped them. Since they are not visual controls they are not shown in the form.

 Pic02.JPG

Place a text box as shown in the picture, set the multiline property to true then resize the text box. Place a PictureBox control on top of the text box control and resize it to the same size of the text box. I hope the other controls and their placement can be done easily. Let us go to the coding part: you can explore coding steps by searching the tag: //File 0

3. The System.IO namespace

This name space is used to access all the functionality for the Windows file system. This article makes use of FileStream, StreamReader, StreamWriter and Path class from the IO name space.

So first include this Name space in the form code:

//File 000: Name space required for accessing the Path utility and other file related
// classes.
using System.IO;

4. File open Event Handler

In this event handler first the filters to the File Open dialog is set using the filter property. This property controls what file type a user can select. In our case it is bitmap, jpg and text files. However we have also kept all files as an option. Once the filter is set, the dialog can be opened using the Showdialog method. And the return value constant tells whether the user selected a file and clicked ok or not. In the filter property we set the supported file types in pairs. For example for text files: Text Files(*.txt) | *.txt

//File 001: Use File open dialog to get the file name
private void btnFileOpen_Click(object sender, EventArgs e)
{
    
//001: Check the user selected a file and pressed ok button. Before opening the dialog
    //      set the filters
    dlgFileOpen.Filter = "Bitmap Files(*.bmp)|*.bmp|Other Image Files(*.jpg)|*.jpg|" +
        "Text Files(*.txt) | *.txt|All Files(*.*)|*.*";
    if (dlgFileOpen.ShowDialog() == DialogResult.OK)
    {

Note: "All Files" in the filter is intentional to show it's use in the FileOpen dialog.

Then using the Path utility class's GetExtension method, the extension of the selected file is extracted. When the extension is not txt we are loading the image file using the Picturebox control. The Filename property of the file open dialog will have the selected file name. And that property is referred in the picture box's load method call. The code is shown below:

 if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
txtSelectedFile.Text = dlgFileOpen.FileName;
string ext = Path.GetExtension(dlgFileOpen.FileName);

if (ext != ".txt")
{
    
//002: If the extension is Bmp or Jpg display it in the Picture box
    txtFileContent.Visible = false;
    pict.Visible = true;
    pict.SizeMode = PictureBoxSizeMode.StretchImage;
    pict.Load(dlgFileOpen.FileName);
}

The else portion clearly says that the selected file is a text file. And, here, construct the StreamReader object by passing the FileStream to the selected text file to the constructor of the stream reader object. The stream object has the ability to read the stream in the form of the text strings. Once we have the stream reader, we read each line of text and display it the multi-select text box. Below is the code:

else
{
    
//003: The extension is txt. Read the file and display the content
    txtFileContent.Visible = true;
    pict.Visible = false;
    FileStream fstream = new FileStream(dlgFileOpen.FileName, FileMode.Open);
    StreamReader reader = new StreamReader(fstream);
    while (reader.EndOfStream != true)
    {
        txtFileContent.AppendText(reader.ReadLine());
        txtFileContent.AppendText(Environment.NewLine);
    }
    reader.Close();

5. FileOk event handler

I can read your mind thinking, "In the previous step this guy sets all files as part of the filter option… and what happens if I select a file that does not fall on any of bmp, txt or jpg file type category?". It will fall in the first portion of if statement and tries to load the file in the picture box getting exception complaints on not a valid image file.

So how do we avoid it? It is simple; remove that last pair in the filter. OK. Anyhow, I kept it to explain the FileOK handler. The FileOK event will be raised once you select the file using the file open dialog. To have a handler on it, select the OpenFileDialog component:

Pic03.JPG 

Then using the property window, double click on the FileOK event (Select the event Icon button first in the Property window). The code the handler is can be easily understood and it is shown below:

//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
    
//001: Get the File extension and test that it falls on required extension
    string Required_Ext = ".txt .bmp .jpg";
    string selected_ext = Path.GetExtension(dlgFileOpen.FileName);
    int index = Required_Ext.IndexOf(selected_ext);
    
//002: Inform the user to select correct extension
    if (index < 0)
    {
        MessageBox.Show("Extension Maaaan... Extension! Open only txt or bmp or jpg");
        e.Cancel = true;
    }
}

COMMENT USING

Trending up