Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

StreamReader and StreamWriter Explained

1. Introduction to StreamReader and StreamWriter

In this article, we will see how to use File Open Dialog and Folder Select Dialog. Also, we will see how do we use FileStream along with  StreamReader and StreamWriter Class. We will also use Path Utility Class, which has a static function to parse the string that comes in the form of a file path.

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

StreamReader StreamWriter Example

StreamReader StreamWriter Example

How it Works?

When we click the ‘…’ button, the example displays a File Open Dialog asking the user to select BMP or JPG image file or a text file. If we select a file other than the above specified three formats, the application will display an error message and File Open Dialog still stays to select a different file. When the user picks a text file, we will display it in the top portion of the dialog. This is shown in the above screenshot. When we select a BMP or JPG file, we display the selected image instead of the text.

The Save File button will save whatever text content displayed in the multi-line text box to a disc file. It takes the filename from the Save File Name text box and saves that in a text format. Before saving, it will ask us to select a folder by displaying the Folder Select Dialog. Once the file is saved, the saved location shown below in a label. The ‘Save in Temp Path’ button saves the file in the system temporary path. OK. Let us start developing this example.

2. Designing the Form

First, we start a Visual C# Windows application and 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 its default (The bold values in the property window) and use it to design the form. Below is the short guidance.

The Components ‘OpenFileDialog’ and ‘FolderBrowserDialog’ are accessible under the ‘Dialogs’ group in Visual Studio Toolbox. We should drag and drop these two Components to the form to use it later. And these controls are shown below the form once we dropped it. As it is a component, it will not occupy any space in the form. Besides, it shows up at the bottom of the designer. The below picture shows the component location in the Toolbox:

OpenFileDialog & FolderBrowserdialog in Toolbox

OpenFileDialog & FolderBrowserdialog in Toolbox

Place the text box as shown in the picture in the introduction section. Next, we have to set the multi-line property to true then resize the text box. Next, we place a PictureBox Control on top of the TextBox Control and resize it to the same size of the text box.

Youtube: Demo

3. The ‘System.IO’ Namespace

We use the ‘


’ NameSpace to use all the functionality packed towards the Windows file system. This article uses FileStream, StreamReader, StreamWriter and Path class from the System.IO NameSpace. So first we include this Namespace in the form code:

4. Selecting a File Name

In this section we will select a file from the windows file system. We will allow to select only a text or image file and then display the selected file content in the form.

4.1 OpenFileDialog File Filter

In the click event handler for the button ‘…’, first, we set the filters to the


 dialog using the ‘

Filter Property

’. This property controls what file type a user can select in the


. In our case, it should be the BMP, JPG or TXT file. Once the filter is set using Filter Property, we can open the OpenFileDialog using the


 Function. The return value constant tells whether the user selected a file and clicked OK or cancelled the dialog. In the Filter Property of the OpenFileDialog, we set the supported file types in pairs. For example, for text files, it is

Text Files(*.txt) | *.txt


Youtube : FileFilters in OpenFileDialog

4.2 File Name Extension

When user picked a file, we enter inside the conditional code block for


. Inside this conditional block, using the Path utility class’s


Method, the extension of the file is obtained. When it is not text, we are loading the image file using the PictureBox Control. The


Property of the


will have the selected filename. And we pass on this Property in the picture box’s


 function call. The code is below:

YouTube: Display Picture or Text?

4.3 Read Text File Using StreamReader

In the else portion, we deal with the text file. And, here, we construct the


object by using the selected file. We use this FileStream to construct the


. The


object can read the stream in the text’s form using FileStream. Once we have the StreamReader, we read each line of text using


  Method and display it in the multi-line text box. We end the loop by checking the


 Boolean value. Below is the code:

Youtube: Demo

5. FileOK Event Handler for OpenFileDialog

One may think, “In the preceding section we set all files as part of the filter option (All Files(.)|.) What happens if our user selects a file that does not fall on any of the supported file category?”. It will fall in the first portion of the if statement. The code tries to load the file in the picture box throwing exception stating not a valid image file.

So how do we avoid the invalid file format exception? The simple solution is removing the last pair from the Filter Property. But, we kept this to study the need of


Event. C# will raise it once the user picks a file using the


. This handler is the perfect place to validate the selected file and guide our user. Follow the below steps to handle



  1. Select the OpenFileDialog Component as shown in the below picture:
  2. Select the event Icon in the Property window.
  3. Then using the property window, double click on the FileOK Event.
OpenFileDialog Component

OpenFileDialog Component

The above steps will land us in the


Event Handler. Here, we make sure user picks a txt or bmp or jpg image. When the user picks files other than these formats, we set


Property of the


to true. This will instruct the C#


 not to set its


 Property with this user selected file. Before cancelling the user selection, we guide the user to select a correct file format using a message box. Below is the code:

Youtube: Demo

6. Save Text File Using StreamWriter

In the early part, we saw how to use built-in Dialog to open a file and then read the text file using the StreamReader object. Also, we saw the need for FileOK Event Handler where we can do acceptance for the picked file. Now, we will go on with the usage of the FolderBrowserDialog Component and StreamWriter object.

6.1 Picking a Folder to Save Text File

First, we drag & drop the FolderBrowserDialog Component from the toolbox to the form. Then we set the properties for it by referring the downloaded example. We can find this Component under the Dialogs Group in the Visual Studio toolbox. After setting all the properties, we write the handler for the Save File button.


Description Property

of the Folder Browser Dialog sets the heading of the dialog. We can put an informative text to help the user so they know what they will do with this dialog. As we will save the text file under the selected folder, we set this Property as ‘Select a folder for Saving the text file’. We use the


 Property to set the topmost node of the directory tree. Below is the code:

6.2 ShowDialog of FolderBrowserDialog

Once we set the RootFolder for the


, we call


Method to display it. One can test the return value of the


  to tell, how the dialog was closed by the end user. This means, we can say whether the user selected a Folder and clicked OK or they clicked the cancel button. Once we make sure that the user selected a valid Folder, we store it under a local variable by reading the


 Property of the FolderBrowserDialog. The code is below:

The below picture shows the display of FolderBrowserDialog:

C-Sharp Folder Browser Dialog

C-Sharp Folder Browser Dialog

Youtube: Demo

6.3 Call SaveFile Custom Function

Finally, we make sure that application is not displaying the image. When we know the content is a text, we make a call to the SaveFile Function which we will write next. This Function accepts a path as a parameter and then saves the file in the specified path by taking the filename from the user input given in the text box.

6.4 Write Text File Using StreamWriter in the Selected Path

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


object for the given file is created with the path selected by the


. Note that, this time we asked


constructor to create a new file using


enumerated constant. Once the


is ready, we connect it to the


for the writing the text content displayed in the Multi-Select text box to it. Using the


  Method on the


 entire content of the Multi-line text box is written to the Specified text file. The Label Control at the bottom of the form displays the saved path.

Youtube: Demo

7. Handler for ‘Save in Temp Path’ Button

In this button handler, we first take the windows temporary path for the logged in user. The


  API will help us in retrieving the required path. Finally, we make a call to our SaveFile Function by supplying this Temporary Path. Below is the code:

Source Code Example: Download From Google Drive

Categories: C#

Tags: , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.