© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
Common Dialog Windows
The windows that appear in most standard applications, such as
those that enable fonts to be changed, files to be opened and
files to be saved, are called Common Dialogs, Dialog Boxes or
Dialog Windows. The code within any application can include
commands that display a named Dialog Windows that has been
added to the application form.
In the toolbox the available dialogs are listed in the expanded
Dialogs section as shown opposite. Individual Dialogs are added
to an application form in the same way as any control would be
added. That is, double click on its name or click once on its name
and drag it to the form. When this is done nothing appears on
the form itself but the default Dialog name will appear under the
form as shown below.
Clicking on a specific Dialog name from those added to the
form will cause its properties to be displayed in the Property
Window (usually under Solution Explorer). The
PropertyWindow can be used to give a Dialog a more
descriptive name but this is rarely done. The only property
commonly altered is the Title property of the file open and
close dialogs. This provides the text that appears in the
Dialog Window’s title bar. For example, for a file opening
dialog this property could be changed to “Select the file to
be opened”.
The statement from within the application that causes a Dialog Window to be displayed is:
dialog_name.ShowDialog();
For example, to display the Dialog named ColorDialog1, shown below the form above, would
require the statement:
ColorDialog1.ShowDialog();
Once a Dialog Window is opened nothing can be done on the form whose code requested
it’s display until the Dialog Window is closed, after which execution continues with the
statement following the ShowDialog(); statement. Properties changed through the Dialog
Window are usually then assigned to other form items as is illustrated in the example below.
Example 1
Create an application with a form similar to that shown
opposite. When the Change Textbox Font button is clicked the
font in the name text box is to change to that selected from a
Dialog Window. Similarly when the Select a Picture button is
clicked, the picture box is to display the image in file selected
via an Open File Dialog Window.
C# Programming – Text File Access
Page 2 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
Possible code for the two button click event functions is shown below.
private void btn_change_font_Click(object sender, EventArgs e)
{
// Display the font dialog window
fontDialog1.ShowDialog();
// Change the text box font to that selected in the font dialog
txt_name.Font = fontDialog1.Font;
}
private void btn_select_picture_Click(object sender, EventArgs e)
{
// Change dialog window title (could have been done via its properties
openFileDialog1.Title = “Choose the image to be displayed”;
// display the Open file dialog window
openFileDialog1.ShowDialog();
// put into the picture box the image held in the file selected
pic_display.Image = System.Drawing.Image.FromFile(openFileDialog1.FileName);
}
Note that the Dialog properties fontDialog1.Font and openFileDialog1.FileName altered via
the Dialogs are assigned to or used to alter application Form control properties.
Open the example (Dialogs Example on the shared drive) and run it to see the actions.
Exercise Set A
- Take a copy of the supplied application Dialog Example and add two new buttons.
One that allows the user to choose a background colour for the form and one which
allows the user to choose a colour for the text entered into the text box.
Text File Access in C#
C# can create or use the contents of files stored in text (character) or binary formats. Text
files are commonly stored as a series of lines, that is, groups of characters (bytes) separated
by new line (CR & LF) characters. They can be created using a text editor (such as
notepad). Binary files store numbers and non character data in their machine internal binary
form rather than in people understood text format. Thus binary files commonly have records
that are a fixed number of bytes rather than placing records on separate “lines” (using CR/LF
as a record separator).
Files can be access sequentially or randomly. Sequential access means a file must be
written or read from start to finish. For example, if the 6th line in a sequential file is required,
it can only be reached by firstly reading the 5 lines above it. Random access means the
program can jump to any designated record position in a file without having to read or write
the records stored above it.
C# Programming – Text File Access
Page 3 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
We will initially consider only simple sequential access text files. In C# such files are called
byte streams since the system treats their contents merely as a transmission (stream) from
the storage device of consecutive characters (bytes). Note that keyboard input and monitor
output are also treated as a byte streams, hence the commonality in the methods (functions)
used for console IO and text file IO.
Within C# the supplied methods and types need for text file access are not automatically
made available to applications. To make them available requires the added namespace
directive:
using System.IO;
Place this directive in the code file for the form after all the other “using” statements that
appear before the “namespace” declaration line.
In general file access involves the following ordered steps: - Declare file variables
- Open the file
- Read data from or write data to, the file
- Close the file
Declaring File Variables
When using text files in a C# application the file has two names associated with it. The first
is the name (and path) of the file as it is known as by the operating system, for example,
names.txt or c:my documentsnames.txt. The second is a variable name used within the
application to refer to the file.
To read data from a text file requires a variable of type StreamReader to be declared and
to write to a text file requires a variable of type StreamWriter be declared.
Example declarations are:
StreamReader in_file;
StreamWriter out_file;
In most cases all file reading/writing will be within a single event and so the StreamReader
and/or StreamWriter variable(s) will be local variables within a single event function. They
will only have to be made form variables in the rare situation where the file is to be accessed
from within different application events (or functions).
Opening a File
File opening statements reserve the RAM space needed by the system to receive the text
data sent from a file or to hold the text data being sent to a file. They also connect each
system file name to their matching application StreamReader or Streamwriter variable
name. In most applications opening the file should usually only occur ONCE for each file
Input text files are opened using the statement
C# Programming – Text File Access
Page 4 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
StreamReader_variable = File.OpenText (System_filename);
Output files are opened using the statements
StreamWriter_variable = File.CreateText(System_filename);
Or StreamWriter _variable = File.AppendText(System_filename);
It is important to realise that if File.CreateText() is used, it creates a new empty system file
with the specified name (and path). If a system file with that name (and path) already exists
it is deleted and a new empty file with that name created. File.AppendText() attaches file
output to the end of any existing system text file with the specified system name or creates
a new empty file if the system file named does not exist.
Closing a File
This action transfers from RAM any output data not yet written to an output file and then for
both input and output files, de-allocates the RAM space used during file access that was
allocated by the file opening process. To close a file in C# requires the statement:
StreamReader_variable.Close();
or
StreamWriter_variable.Close();
Writing Data to a Text File
Data can be sent to a text file character at a time or string at a time. This can be done by
using one of the statements:
StreamWriter_variable.Write(item);
or
StreamWriter_variable.WriteLine(item);
where item is a string expression or a character constant or a character variable.
Write(item) sends item to the file and the NEXT output value will immediately follow it (on
the same line).
WriteLine(item) sends item to the file and THEN goes to a new line in the file ready for the
next output value. That is, the NEXT output value will start on a new line following the text
sent to the file by this statement.
To insert a blank line in an output file omit item. That is, use the statement:
StreamWriter_variable.WriteLine();
C# Programming – Text File Access
Page 5 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
File Write Example 1 (Test the example by running the application File Access Ex 1 on the
shared drive.)
Create an application that initialises a string array holds a set of 5 names (“Al”, “Di”, “Jo”,
“Bo” and “Fi”). When a button is clicked the names are to be transferred to a text file chosen
through a Save File Dialog Window.
A possible form is as shown opposite and
coding for the button’s click event function as
below. Note that the “using System.IO;”
directive would have to be added.
private void btn_write_file_Click(object sender, EventArgs e)
{
string[] names = { “Al”, “Di”, “Jo”, “Bo”, “Fi” };
int s;
StreamWriter OutFile;
MessageBox.Show(“An array holds the names Al, Di, Jo, Bo, and Fi ” +
“nThese will be written to a file”); saveFileDialog1.Title = “Choose file to which the names are to be written”;
// could do this instead by altering the Title property in Form design view saveFileDialog1.ShowDialog(); // open the file chosen though the dialog box
OutFile = File.CreateText(saveFileDialog1.FileName);
for (s = 0; s < 5; s++)
{
OutFile.WriteLine(names[s]);
}
OutFile.Close();
MessageBox.Show(“Names written to file ” + saveFileDialog1.FileName);
}
Exercises Set B - Create an application as follows. When the user enters a person’s name and age
into two text boxes and clicks on an “accept” button these entries, separated by a tab
are to be transferred to a list box. After repeating this action the desired number of
times, when a second “Send to File” button is clicked the list box items are to be
written one per line to a file chosen through a Save File Dialog Window. - Repeat Question 1 but write the list box items in the file two per line separated by
two tabs. Also include in the file a first line that holds appropriate column headings
for the columns of names and ages. - Create an application that at start up asks the user to choose an output file using a
Save File Dialog Window. The application to have a “Write to File” button that when
clicked will take a name and age that the user has entered into two text boxes and
write them directly to the file. The user can repeat the button click action as often as
C# Programming – Text File Access
Page 6 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
they wish. Think carefully about the event in which the file needs to be opened and
closed. - Repeat Question 3 but this time allow the names to be added to the end of an existing
file.
Reading Data from a Text File
Data can be read from a text file
line or at a time. OR
character at a time
Reading a Text File Line at a Time
To read a complete line of text from an input text file (into a variable of type string) use the
code
string_var = StreamReader_variable.ReadLine();
Where a text file line holds multiple fields then it must be created having:
Fixed widths ( a specified numbers of characters) for each field OR
A specific separating character between fields (e.g a comma or space)
String handling functions will then have to be used to separate the individual fields into
separate strings. Numeric fields will also have to be converted from strings to numbers.
Be aware that an application can only be created that reads and processes a file line at a
time when the structure of each line is known.
File Read Ex 1 (only one data item per file line)
A text file has a single name on each of its lines. Create an application that allows the
user click on a button that will then allow the user to
select this file using an open file dialog window and
display the names it holds in a list box.
Solution (this application can be tested by running the
application File Read Ex1 that can be found on the shared
drive).
A possible form for this application is a shown opposite and
the button’s click event function code as shown below.
private void BtnReadFile_Click(object sender, EventArgs e)
C# Programming – Text File Access
Page 7 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
{
string str_name;
StreamReader in_file;
openFileDialog1.Title = “Choose file names are to come from”;
openFileDialog1.ShowDialog();
if (File.Exists(openFileDialog1.FileName)) //if file chosen exists
{
in_file = File.OpenText(openFileDialog1.FileName);
str_name = in_file.ReadLine(); // read the first file line
while (str_name != null) // continue provided a name exists
{
lst_names.Items.Add(str_name);
str_name = in_file.ReadLine(); // read next file
}
in_file.Close();
}
else
{
MessageBox.Show(“No file was chosen”);
}
}
In the above code File.Exists(system_file_name) is a supplied Boolean function that
returns true if a file with the name and path held in system_file_name exists. If it does not
then the usual step is to display an error message.
The logic flow for reading from a file is as follows: - Read the first file line into a string – if the file holds no data this string will be empty
(it will hold the null string). - If the file line is not empty, the loop is entered and its statements executed. The loop
statements will contain:
statements that process the line of text read from the file, followed by
a statement to read the next line of text from the file - Step 2 is then repeated until the line read from the file is empty. That is, the file holds
no more lines of text.
C# allows the code for the file reading and processing steps to be shortened, by combining
the reading of the file line and the testing to determine if the string read was empty. The
shortcut code is as follows:
while ((str_name = in_file.ReadLine()) != null)
{
lst_names.Items.Add(str_name);
}
C# Programming – Text File Access
Page 8 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
In testing the above while loop condition, the assignment statement
(str_name = in_file.ReadLine())
is executed first. The value assigned to the string variable str_name is then tested to see if
it is not empty (!=null).
File Read Ex2 (multiple data items per file line)
A text file holds records, one per line, that respectively hold, separated by commas, fields
holding a name, age, height and weight. Create an application that when a “Show File
Data” button is clicked, allows the file to be selected using an “Open File” dialog window. It
must then read from the selected file its records and transfer all the names to a list box and
display in separate text boxes the average age, height and weight for the people whose
records are held within the file.
Solution
A possible form for this application is a shown below and the button’s click event function
code is also shown below. Within this code the lines in the file are read one at a time and
processed. Each line from the file is broken into its individual fields usings the string handling
.Split() function and those fields then processed.
The full code for this example can be viewed and tested by the application File Read Ex2
that can be found on the shared drive. private void btn_display_file_Click(object sender, EventArgs e)
{
string str_file_line;
int int_age_total = 0, int_count = 0; ;
float flt_height_total = 0, flt_weight_total = 0;
float flt_average_age, flt_average_height, flt_average_weight;
StreamReader in_file;
openFileDialog1.Title = “Choose the file holding the names”;
openFileDialog1.ShowDialog(); if (File.Exists(openFileDialog1.FileName))
C# Programming – Text File Access
Page 9 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
{
in_file = File.OpenText(openFileDialog1.FileName);
// file lines have format name,age,height,weight (comma separates fields)
while ((str_file_line = in_file.ReadLine()) != null)
{
string[] line_fields = new string[4]; // string array to hold the fields
// separate the str_file_lineinto separate strings (comma separator)
line_fields = str_file_line.Split(‘,’);
// send the name (line_fields[0]) to the list box
lst_names.Items.Add(line_fields[0]);
// convert age string (line_fields[1]) to integer-add to age total
int_age_total += int.Parse(line_fields[1]);
// convert height string (line_fields[2]) to float – add to height total
flt_height_total += float.Parse(line_fields[2]);
// convert weight string (line_fields[3]) to float-add to weight total
flt_weight_total += float.Parse(line_fields[3]); int_count++; // increment the record count
}
in_file.Close();
// calculate the averages
flt_average_age = (float)int_age_total / (float)int_count;
flt_average_height = flt_height_total / (float)int_count;
flt_average_weight = flt_weight_total / (float)int_count;
// Display the averages
txt_average_age.Text = flt_average_age.ToString(“F2”);
txt_average_height.Text = flt_average_height.ToString(“F2”);
txt_average_weight.Text = flt_average_weight.ToString(“F2”);
}
else
MessageBox.Show(“No file was chosen”);
}
Exercise Set C - The file “products1.txt” contains a list of product names one per line. Create an
application that allows the user to select this file using an “Open File” dialog window
and click a “Display Products” button to transfer the product names the file contains
to a list box. Clicking a second “Sort Products” button must sort the list box product
names into alphabetical order (Hint: alter the list box’s “sorted” property). - Repeat Question 1 but this time there is no “Display Products” button and the names
are to be transferred from the file “products1.txt” directly on the start-up of the
program. (No “Open File” dialog window is used to choose the file.)
C# Programming – Text File Access
Page 10 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx - The file “products2.txt” has lines holding a product name and price (without a $ sign),
the two fields separated by a comma. Create an application that allows the user to
select this file using an “Open File” dialog window and click a “Display Products”
button to transfer the product names and the matching price with a $ sign to a list box
on the form. - The file “products2.txt” has lines holding a product name and price (without a $ sign),
the two fields separated by a comma. Create an application with a form that holds a
text box, button and list box. At startup the file contents are to be copied into two
parallel arrays, one holding the product names and the other the prices. After the
user enters a numeric value into the text box, clicking the button is to cause the list
box to be cleared and the product names and their matching prices of all the products
in the product array with a price less than the entered value to be displayed in the list
box. - Create a text file that has lines containing, in order, a family Name, Given name and
student test mark, the separate fields having a comma between them. Create an
application that reads these records into parallel arrays and then sends to a list box
the given and family names of those with an above average mark - Alter the application in Question1 by adding a “new Product” text box and an “Add
New Product” button to the form. After the user has entered the name of a new
product into the text box clicking on the button is to add the entered product name to
the list box and append the name to the “products1.txt” file. (Consider carefully
where the file, when used for output, should be opened and closed bearing in mind
this should only happen once and AFTER all the existing data has been read from
the file.) - Create a simple C# application that reads a text file of characters line at a time and
sends it to a new file with every upper case character changed to a lower case
character except if one of the following occurs:
it is the first character in the file
It is the first character on the line and the last character on the previous line
was a full stop character.
it is preceded by a full stop and two spaces
it is preceded by a full stop and one space.
Reading a Text File Character at a Time
To read a text file one character at a time requires the input to be assigned to an integer
variable (type int) with the code
int_var = streamreader_variable.Read ();
After reading, the integer variable MUST be changed to a character for processing by type
casting it to a character with the expression
char_var = (char) int_var;
C# Programming – Text File Access
Page 11 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
If there is no data remaining in the file then int_var will have -1 sent to it. Hence the
statement
int_var = streamreader_variable.Read ();
needs to be repeated until int_var holds -1.
Read File Ex 3 (Reading a text file character at a time)
Create an application that copies, character at a time, the contents of a file the contents of
a file selected through an “open File” dialog window into a rich text box.
Solution
A possible form for this application is as shown
opposite and the button’s click event function code as
shown below.
This application can be tested by running the
application Read File Ex3 that can be found on the
shared drive.
private void btn_display_file_Click(object sender, EventArgs e)
{
int int_char;
char ch;
StreamReader in_file;
openFileDialog1.Title = “Choose the file to copy”;
openFileDialog1.ShowDialog();
if (File.Exists(openFileDialog1.FileName))
{
lbl_contents.Text = openFileDialog1.FileName + ” contents”;
C# Programming – Text File Access
Page 12 of 12 Cert III in IT – Week 16
© Brian Kaye F:Teaching SubjectsCert III C#Sem 2 2014lecturer versionWeek 16 Text FilesWeek 16 – text file access.docx
in_file = File.OpenText(openFileDialog1.FileName);
while ((int_char = in_file.Read()) != -1)
{
ch = (char)int_char;
if (ch != ‘n’)
{
rtb_file_contents.Text = rtb_file_contents.Text + ch;
}
}
in_file.Close();
}
else
{
MessageBox.Show(“No file was chosen”);
}
}
Note in the above code the if statement
if (ch != ‘n’)
{
rtb_file_contents.Text = rtb_file_contents.Text + ch;
}
This is included since pushing the enter key on the keyboard generates two characters, one
of which is the new line character ‘n’. Both of the two characters cause the output of a new
line so one (the ‘n’) can be ignored.
Exercise Set D - Create a simple C# application that encrypts a file using a simple circular encoding
method as follows. Any upper case alphabetic character it contains is to be converted
to its equivalent lower case value followed by a “+” sign, then each alphabetic
character by replaced by the letter that is 5 characters further on in the alphabet. For
the letters v, w, x, y and z, rotate to the start of the alphabet replacing them in turn by
a, b, c, d and e. A space character is to be replaced by “+x”, a full stop by “*y” and a
comma by ”-z”. Any other character in the file apart from those listed above are to be
copied to the new file unchanged. The program must allow the user to choose the
names of the input and output files. - Create an application that takes a file created by the encryption application of
Question 1 and returns it to its unencrypted state. The program must allow the user
to choose the names of the input and output files.