File IO Lab
In almost every program that you will write, you will need to perform some type of Input Output (IO) operations. Be it in the form of data being passed from the user typing in commands at the keyboard or information being displayed to the user in the form of text on the screen, or information being pulled in and/or pushed out to a file. In this lab you will be exposed to the concept of getting data from and sending data out to a file.
As you would expect File IO is the process where by we can read in data from a file and use that data in our program, like when there is a NFO file that tells a program how to start up, or save data out to a file for storage for later retrieval, like when you save a word document while working on your term paper. Now that we have covered what File IO is lets actually start putting this to use.
First you will need to open C# and create a new Windows Application, keep in mind that reading from and writing to a file in a console application would use the same File Access code that will be used in this lab. Once your new application is open you will need to make it where you can use the File IO data types and procedures. To do this you need to add the highlighted line of code to your using statements.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
Now that you have told your application that you will be using IO commands we can proceed. First we need to create a variable of type FileStream and tell it what file to open, where the file is and, how to open it, and what type of Read/Write permissions it has. The below line of code declares and sets up our FileStream for us.
FileStream file = new FileStream("TheIOFile.txt", FileMode.Open, FileAccess.Read);
As you can see creating a FileStream is the same as creating any complex data type in C#. Now that you have created a FileStream let’s see what each parameter in the above code means. As you might have already guessed ("TheIOFile.txt") tells the program where the file is and what file to open. In this case we are telling the program to go the working directory of the program and open the file called TheIOFile.txt, as for what is the working directory of the program that all depends on how you ran the program. If you pressed F5 to run the program then the working directory is the debug folder (C:\Documents and Settings\username\Desktop\FileIOLab\FileIOLab\bin\Debug if your program was saved to the desktop), however if you pressed Ctrl-F5 to run the program then the working directory is the release folder (C:\Documents and Settings\username\Desktop\FileIOLab\FileIOLab\bin\Release if your program was saved to the desktop). The next parameter (FileMode.Open) tells the program how to open the file. There are six different options for this parameter and they are Append (tells the program to open the file so as to add data to the end of the file, use only if the file already exists), Create (tells the program to create the file and then open it, if the file already exists it will be over written), CreateNew (tells the program to create the file and then open it, use this only if the file does not already exist), Open (tells the program to open an existing file, use this only when the file exists), OpenOrCreate (tells the program to open the file if it exists otherwise create it), and Truncate (tells the program to open an existing file and overwrite the current data). For this lab we will use the Open option since we know that the file will already exist and since we do not want to over write the data that is contained in the file. The next parameter (FileAccess.Read) tells the program what read/write permission it has through this FileStream. For this parameter there is only three possible options and they are Read (only allows the program to read from the file), Write (only allows the program to write to the file), ReadWrite (allows the program to read and write from the file). For the first part of this program since we only need to read from the file we will set this option to Read.
Now that we have created the connection to the file we need to create a way to
access all the information contained in the file. To do this we need to
create another variable, this one of type StreamReader.
StreamReader reader = new StreamReader(file);
As you can see in the above code this type of variable only needs one parameter to set up and that is the stream that we will be reading the data from, which in this case is our variable file that we created earlier.
Now that we have created these two variables the connection to the file has been completed HOWEVER before we can run our program there are still three last things that we must do. First we most close the StreamReader and then the FileStream. This is accomplished by issuing the Close command as can be seen in the below code.
reader.Close();
file.Close();
Next we need to get the text file that we will be using in this lab and place it in the working directory of our program. You can obtain this file here.
At this point your program’s code should currently look like the code below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIOLab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FileStream file = new FileStream("TheIOFile.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
reader.Close();
file.Close();
}
}
}
Once your code looks similar to the above code AND you have downloaded the file we are using to your working directory you can now compile and run your code at which time you will be greeted with the below window.

Once you have run your program and it has executed successfully, meaning it did not crash saying it could not find the file, you can close the window and we can continue.
Now that we have set up the connection to our file wouldn’t it be nice if we could actually read the data from the file we have worked so hard to connect to? To do this we need to tell the program to read each line of the file until we reach the end of the file. To do this we need only to tell our StreamReader to read until it has reached the end of the file. In order to accomplish this we will need to use a While Loop and have the loop continue until the end of the file is reached.
while (!reader.EndOfStream)
{
}
As you can see in the above code we tell the while loop to continue looping while EndOfStream is False by using the Not (!) operator. By doing this each time the EndOfStream returns False the False will be turned into a True by the Not (!) operator and the loop will continue since it’s loop condition is still True.
Now that we have told the program to read each line of text in the file we can now get all the data out of our file for use in our program. In order to accomplish this we will need to use the ReadLine() command of the StreamReader. Also we will need to store the data we get out of the file, which we will do at this point with a temporary String variable. Also to show that we are really reading the data out of the text file we will have the data printed out to a MessageBox as it is read out of the file.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIOLab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
FileStream file = new
FileStream("TheIOFile.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new
StreamReader(file);
while (!reader.EndOfStream)
{
string temp = reader.ReadLine();
MessageBox.Show(temp);
}
reader.Close();
file.Close();
}
}
}
Once you have entered the highlighted code you can now run your program and you should see the following MessageBoxes:


Once you finish going through each MessageBox the form will come up at which time you should close it.
Now that we can read each line of the text file we now need to store the data we are getting out of the text file so as we can use it later on in the program. In order to do this we will need to create two variables of type int and also as we are reading in the data from the text file we will need to convert the string data we are reading into an int. In order to accomplish the conversion we will need to use the ToInt16 command of the Convert class, which is formatted like the below code:
Convert.ToInt16(reader.ReadLine());
By using this line of code we can now store the numbers in the text file in our integers. Also we will need one more int in order to keep track of which number we are currently reading.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIOLab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
FileStream file = new
FileStream("TheIOFile.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new
StreamReader(file);
int firstNumber = 0;
int secondNumber = 0;
int numberOn = 0;
while (!reader.EndOfStream)
{
int temp = Convert.ToInt16(reader.ReadLine());
if (numberOn == 0)
{
firstNumber = Convert.ToInt16(temp);
numberOn++;
}
else
{
secondNumber = Convert.ToInt16(temp);
}
}
reader.Close();
file.Close();
}
}
}
Now that we
have our data from the text file why don’t we actually do something with
it? In this lab we will use the numbers that
we got from the text file as the bounds for a two dimensional array, then we
will use two For Loops, one
nested within the other to populate the array with data. After the array is populated we will then
print this data out to a MessageBox so as we can view the array we have
created. Below you will find the
expanded code that populates the array and then prints out the information in a
MessageBox.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIOLab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
FileStream file = new
FileStream("TheIOFile.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new
StreamReader(file);
int firstNumber = 0;
int secondNumber = 0;
int numberOn = 0;
while (!reader.EndOfStream)
{
int temp = Convert.ToInt16(reader.ReadLine());
if (numberOn == 0)
{
firstNumber = Convert.ToInt16(temp);
numberOn++;
}
else
{
secondNumber = Convert.ToInt16(temp);
}
}
reader.Close();
file.Close();
int[,] testArray = new int[firstNumber,
secondNumber];
for (int
i = 0; i < secondNumber; i++)
{
for (int
j = 0; j < firstNumber; j++)
{
testArray[j, i] = i + j + 1;
}
}
string stringWriting = "";
for (int
k = 0; k < secondNumber; k++)
{
for (int
l = 0; l < firstNumber; l++)
{
stringWriting = stringWriting + testArray[l, k].ToString() + " ";
}
stringWriting = stringWriting + "\r\n";
}
MessageBox.Show(stringWriting);
}
}
}
Once you have entered the above highlighted code you should get a MessageBox that looks like the one below.

So far we have read from a file and used the data that we obtained from that file for processing within our program, now we need to go the final step and actually save this data out to a file. To do this all we need to do is slightly modify our FileStream and create a variable of type StreamWriter.
file = new FileStream("OutputFile.txt",
FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(file);
This time we are telling our FileStream that it is supposed to connect to a file called "OutputFile.txt" that it is supposed to create that file and that it has permission to only write to the file. Then we create our StreamWriter and set its one parameter to our FileStream just like we did for the StreamReader earlier in our program. Thus with these two variables we now have a connection to our new file and can now write out data to our new file with the Write command. Now let’s finish up our program by inserting the last bit of code into our program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIOLab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
FileStream file = new
FileStream("TheIOFile.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new
StreamReader(file);
int firstNumber = 0;
int secondNumber = 0;
int numberOn
= 0;
while (!reader.EndOfStream)
{
int temp = Convert.ToInt16(reader.ReadLine());
if (numberOn == 0)
{
firstNumber = Convert.ToInt16(temp);
numberOn++;
}
else
{
secondNumber = Convert.ToInt16(temp);
}
}
reader.Close();
file.Close();
int[,]
testArray = new int[firstNumber,
secondNumber];
for (int i = 0; i
< secondNumber; i++)
{
for (int j = 0; j
< firstNumber; j++)
{
testArray[j, i] = i + j + 1;
}
}
file = new
FileStream("OutputFile.txt",
FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(file);
string stringWriting = "";
for (int k = 0; k
< secondNumber; k++)
{
for (int l = 0; l
< firstNumber; l++)
{
stringWriting = stringWriting + testArray[l, k].ToString() + " ";
}
stringWriting = stringWriting + "\r\n";
}
writer.Write (stringWriting);
MessageBox.Show(stringWriting);
writer.Close();
file.Close();
MessageBox.Show("File
created let's see the output");
Close();
}
}
}
After you have entered the highlighted lines of code into your program you can now run your program. After you the second message box comes up you will notice that the form no longer shows this is because at the very end of the code that you entered you issued the Close command that told the form to close. The reason that this line of code is present is because for this program we really do not need to see the form at all, so after you close the final message box you can now go to your working directory and open the "OutputFile.txt" and see the output that the program generated.
With that you are done with this lab, just remember that every time that you open a file once you are finished reading or writing to the file to IMMEDIATELY CLOSE THE FILESTREAM AND THE STREAMREADER AND/OR STREAMWRITER.