Thursday, January 20, 2011

[C#] - Stream Reader, Stream Writer and OpenFileDialog, FolderBrowserDialog

1. Introduction

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

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

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 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 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 select the folder by displaying the Folder Select dialog. Once the file is saved, the saved location 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).

Below is the short guidance:

The "OpenFileDialog" and "FolderBrowserdialog" are available under the dialogs group in your toolbox. Drag and drop those controls to the form. And these controls are shown below the form on you dropped it. As it is not a visual control it will not appear in the form.

Place 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 all other control and its 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 packed towards 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 a bitmap, jpg and text files. However, a just kept all files as also 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 file in the filter is intentional to explain you one of the important event on 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;

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:

    //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)

5. FileOk event handler

I can read some of your minds 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:

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;

6. Stream Writer

In the previous part we saw how to use FileOpen dialog and then read the text content using the StreamReader object. Also we saw an important FileOK event handler where we can to validation for the selected file. This article is the continuation of the previous article, but you can still read it and know the usage of the Folder open dialog and StreamWriter object.

The screen shot is shown here for the continuation.

7. Save File button Handler

1) First, drag and drop the FolderBrowserDialog component (Control) from the toolbox to the form. Set the properties for the control by referring the downloaded application. This component can be found under the dialogs group in your toolbox. Once this is done provide the handler for Save File button.

The description property of the FolderBrowserDialog set the heading for the dialog. You can place an informative text to help the user to make their folder selection. As we are going to save the text file under the selected folder, I kept the text relevant to that. The "RootFolder property" is used to set the topmost node of tree display of the directory. Below is the code:

//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;

2) Once the RootFolder for the Folder dialog is set, display the dialog using the "ShowDialog() method". The return value is tested to tell, how the dialog closed by the end user. Once we make sure a folder is selected and clicking the OK button closed the dialog, we store the selected folder under a local variable using the "SelectedPath property" of the FolderBrowserDialog.

//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
    selected_path = dlgFolder.SelectedPath;
    if (string.IsNullOrEmpty(selected_path) == true)
        MessageBox.Show("Unable to save. No Folder Selected.");

3) Finally, we make sure the displayed content is text. And make a call to the SaveFile function written for this form. The function accepts the path as parameter and then saves the file in the specified path by taking the file name from the relevant text box.

//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
    MessageBox.Show("This form saves only text files");

4) The SaveFile() function first checks the selected path is a root folder (Partition itself. Ex: C:\ or D:\). And based on the test appends a slash at the end of the path. (Debug it to see why?). Then a FileStream object for the given file is created with the path selected by the folder dialog. Note that, this time in the constructor for the FileStream we asked to create a new file using FileMode.CreateNew enumerated constant. Once the FileStream is ready is connected to the StreamWriter for the writing the text content displayed in the multi-select text box. Using the "Write() method" on the StreamWriter entire content of the Multi-line textbox is written in the Specified text file. The saved path is displayed in the Label at the bottom of the form.

//File 005: Save the File to Disk
private void SaveFile(string selected_path)
    string Save_File;
    if (selected_path.Length > 3)
        Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
        Save_File = selected_path + txtSaveFile.Text + ".txt";
    FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);
    StreamWriter writer = new StreamWriter(fstream);
    lblSavedLocation.Text = "Text File Saved in " + Save_File;

8. Save in Temp Path Handler

This button handler just makes a call to the SaveFile function by passing the system’s temporary path. The "GetTempPath() method" of the utility class Path will return the temporary path. Hope, no more explanation is required for this simple function.

//File 004: Save the File in System Temporary path
private void btnTempPath_Click(object sender, EventArgs e)
    if (txtFileContent.Visible == true)
        MessageBox.Show("This form saves only text files");

Note: The application is created in Visual Studio 2005. If you have latest IDE say “Yes” conversion Wizard/Dialog that appears. To know how the Form works read the previous part also.

Source Code : Download

No comments:

Post a Comment

Leave your comment(s) here.

Like this site? Tell it to your Firend :)