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
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
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 ‘
System.IO
’ 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:
1 2 3 |
//File 000: Name space required for accessing the Path //utility and other file related classes. using System.IO; |
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
OpenFileDialog
dialog using the ‘
Filter Property
’. This property controls what file type a user can select in the
OpenFileDialog
. 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
ShowDialog
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//File 001: Use File open dialog to get the //file name private void btnFileOpen_Click(object sender, EventArgs e) { //001a: 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(*.*)|*.*"; //001b: Check the user selected a file and //pressed ok button if (dlgFileOpen.ShowDialog() == DialogResult.OK) { |
Youtube : FileFilters in OpenFileDialog
4.2 File Name Extension
When user picked a file, we enter inside the conditional code block for
DialogResult.OK
. Inside this conditional block, using the Path utility class’s
GetExtension
Method, the extension of the file is obtained. When it is not text, we are loading the image file using the PictureBox Control. The
Filename
Property of the
OpenFileDialog
will have the selected filename. And we pass on this Property in the picture box’s
Load
function call. The code is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//001b: Check the user selected a file and //pressed ok button 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); } |
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
FileStream
object by using the selected file. We use this FileStream to construct the
StreamReader
. The
StreamReader
object can read the stream in the text’s form using FileStream. Once we have the StreamReader, we read each line of text using
ReadLine
Method and display it in the multi-line text box. We end the loop by checking the
EndOfStream
Boolean value. Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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(); } |
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
FileOK
Event. C# will raise it once the user picks a file using the
OpenFileDialog
. This handler is the perfect place to validate the selected file and guide our user. Follow the below steps to handle
FileOK
Event:
- Select the OpenFileDialog Component as shown in the below picture:
- Select the event Icon in the Property window.
- Then using the property window, double click on the FileOK Event.

OpenFileDialog Component
The above steps will land us in the
FileOK
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
Cancel
Property of the
CancelEventArgs
to true. This will instruct the C#
OpenFileDialog
not to set its
FileName
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//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("Open only txt or bmp or jpg"); e.Cancel = true; } } |
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.
The
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
RootFolder
Property to set the topmost node of the directory tree. Below is the code:
1 2 3 4 5 6 7 8 9 10 11 |
//File 003: Open the Folder Dialog to select a //directory for saving the file private void button1_Click(object sender, EventArgs e) { //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; |
6.2 ShowDialog of FolderBrowserDialog
Once we set the RootFolder for the
FolderBrowserDialog
, we call
ShowDialog()
Method to display it. One can test the return value of the
ShowDialog()
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
SelectedPath
Property of the FolderBrowserDialog. The code is below:
1 2 3 4 5 6 7 8 9 10 11 |
//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."); return; } } |
The below picture shows the display of FolderBrowserDialog:

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.
1 2 3 4 5 6 7 8 9 |
//003: Perform the File saving operation. //Make sure text file is displayed before saving. if (txtFileContent.Visible == true) { SaveFile(selected_path); } else MessageBox.Show( "This form saves only text files"); |
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
FileStream
object for the given file is created with the path selected by the
FolderBrowserDialog
. Note that, this time we asked
FileStream
constructor to create a new file using
FileMode.CreateNew
enumerated constant. Once the
FileStream
is ready, we connect it to the
StreamWriter
for the writing the text content displayed in the Multi-Select text box to it. Using the
Write()
Method on the
StreamWriter
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//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"; else Save_File = selected_path + txtSaveFile.Text + ".txt"; FileStream fstream = new FileStream( Save_File, FileMode.CreateNew); StreamWriter writer = new StreamWriter(fstream); writer.Write(txtFileContent.Text); lblSavedLocation.Text = "Text File Saved in " + Save_File; writer.Close(); } |
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
GetTempPath
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
//File 004: Save the File in System Temporary path private void btnTempPath_Click(object sender, EventArgs e) { if (txtFileContent.Visible == true) { SaveFile(Path.GetTempPath()); } else MessageBox.Show("This form saves only " + "text files"); } |
Source Code Example: Download From Google Drive
Categories: C#
Tags: C# FileStream, C# FolderBrowserDialog, C# OpenFileDialog, C# StreamReader, C# StreamWriter