Transcript CIS162AB
CIS162AD - C#
File I/O
11_file_processing.ppt
Overview of Topics
Information Processing Cycle
File Processing (I/O)
CIS162AD
2
Hardware Model
CPU
Input Devices
Memory (RAM)
To this point we have been using the text
boxes for input and picture boxes for output.
Both of these are temporary.
CIS162AD
Output Devices
Storage Devices
3
Information Processing Cycle
Input
Raw Data
Process
(Application)
Output from one process can
serve as input to another process.
Output
Information
Storage
Storage is referred to as secondary
storage, and it is permanent storage.
Data is permanently stored in files.
CIS162AD
4
Input and Output (I/O)
In the prior assignments, we would enter the test
data and check the results.
If it was incorrect, we would change the program,
run it again, and reenter the data.
Depending on the application, it may be more
efficient to capture the raw data the first time it is
entered and store in a file.
A program or many different programs can then
read the file and process the data in different ways.
We should capture and validate the data at its
points of origination (ie cash register, sales clerk).
CIS162AD
5
CS11ex File Processing
We have a file named coffees.txt
The file has 5 coffee names as separate records.
To process the file:
– open file.
– read a coffee name and load it into the combo box.
– need a loop to read and load each record.
– allow users to add and remove coffee names.
– and then save the results back to coffees.txt.
Sequential file Processing – processing the
records in the order they are stored in the file.
CIS162AD
6
coffees.txt
Chocolate Almond
Espresso Roast
Jamaican Blue Mtn.
Kona Blend
Vanilla Nut
This is a simple text file.
The file can be created with Notepad or some
other text editor.
Just enter values and press return at the of each
record, including after the last one.
The file should be saved in the Debug folder
within the bin folder of the project folder.
CS11ex > bin > Debug > coffees.txt
CIS162AD
7
Sample Interface
CIS162AD
8
using System.IO;
The classes for data processing are defined in the System.IO
namespace.
– FileStream, StreamReader and StreamWriter
– IO stands for Input/Output
These class definitions are NOT automatically included in
C# projects.
Insert the using command at the top of program before the form
declaration to utilize the class definitions.
using System.IO;
namespace CS11
{
public partial class frmCS11ex : Form
{
CIS162AD
9
Menu Option: File -> Load List
Use an OpenFileDialog box (Windows 7)
CIS162AD
10
Load File Method – Part 1
private void mnuFileLoad_Click(object sender, EventArgs e)
{
//Not checking if a list has already been loaded
string strFileName;
string strFlavorName;
//Open the file and load the list box with the data stored in the file
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 1; // At first only show text files.
openFileDialog1.InitialDirectory = Application.StartupPath; //default folder
openFileDialog1.RestoreDirectory = true; // restore path to default folder
CIS162AD
11
Load File Method – Part 2
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
strFileName = openFileDialog1.FileName;
FileStream flavorsFileIn = new FileStream(strFileName, FileMode.Open);
StreamReader flavorsStreamReader = new StreamReader(flavorsFileIn);
while (flavorsStreamReader.Peek() != -1)
{
strFlavorName = flavorsStreamReader.ReadLine();
cboCoffee.Items.Add(strFlavorName);
}
flavorsStreamReader.Close();
}
else
{ MessageBox.Show("File not selected; List was not loaded.",
"List Not Loaded", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
} catch
{
MessageBox.Show("Selected file could not be opened.",
"Error Opening File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
CIS162AD
12
Internal and External File Names
coffees.txt is the external file name.
flavorsFileIn is the internal file name.
FileStream flavorsFileIn = new FileStream("coffees.txt", FileMode.Open);
connects the internal name to the external file.
Naming conventions for the external file names vary by
Operating Systems (OS).
Internal names conform to variable naming rules.
In new FileStream is the only place we see the external name.
CIS162AD
13
Use Try/Catch When Opening Files
Some possible errors:
– File not found
– Protection violation on network
– Disk Full
CIS162AD
14
Process the file
When the input is from a file, it is referred
to as the reading the file.
Saving to a file is referred to as Writing
to the file.
In the loop we continue reading the file
until we reach the End Of File (EOF).
EOF flag is set by the operating system (OS)
when the last record is read.
CIS162AD
15
EOF Flag
Flag is a term used for variables that can have two
possible values.
– On or off,
– Y or N,
0 or 1
True or false
EOF? – is it at the end of the file or not?
In this example the Peek method is used to check
for EOF.
Minus 1 (-1) is return when the end of file is reach
while (flavorsStreamReader.Peek( ) != -1)
CIS162AD
16
Close File
flavorsStreamReader.Close( );
Close releases file to Operating System (OS).
Other users may get file locked error if file is
not closed.
Good housekeeping.
CIS162AD
17
cblnIsDataSaved Flag
Need to track when data has been changed, but not
yet saved.
If users Add, Remove, or Clear an item from the list,
the cblnIsDataSaved must be set to false.
In the FormClosing method, the flag is checked and if
it is false the user is asked if they want to save the
changes before exiting.
If the user says yes, then the File Save method is
called.
CIS162AD
18
Form Closing Event
If user’s click on a Close button or Exit menu item, we can
capture those events.
If the user clicks on the close window icon, an event is not
fired.
However, when the form is instructed to close (this.Close), the
Form Closing event is fired, and we can add a handler for that
event.
Create a method and add the code to check if the data has been
saved in the form closing method.
After writing this method to handle the FormClosing event, its
needs to be assigned as the form's FormClosing event handler
while in Design Mode.
After assigning it to the form, the method is automatically
executed when the form is instructed to close.
In the Close button or Exit menu method, just call this.Close( )
and that will trigger the Form Closing event.
CIS162AD
19
Exit and Closing Methods
private void mnuFileExit_Click( … )
{
//cblnIsDataSaved checked in Form Closing event procedure.
this.Close( );
}
private void frmCS11ex_FormClosing( … )
{
DialogResult dgrResponse;
if (cblnIsDataSaved = = false)
{
dgrResponse = MessageBox.Show("Do you wish to save the list?",
"Save", MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (dgrResponse = = DialogResult.Yes)
mnuFileSave_Click(mnuFileSave, new EventArgs( ));
if (responseDialogResult == DialogResult.Cancel)
e.Cancel = true; //cancel close event
}
}
CIS162AD
20
Menu Option: File -> Save List
Use an SaveFileDialog box (Windows 7)
CIS162AD
21
File Save Method – Part 1
private void mnuFileSave_Click(object sender, EventArgs e )
{
string strFileName;
int intIndex, intMaximum;
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1; // At first only show text files.
saveFileDialog1.CheckFileExists = false; // Allow user to create file
saveFileDialog1.InitialDirectory = Application.StartupPath; //default folder
saveFileDialog1.RestoreDirectory = true; // restore path to default folder
CIS162AD
22
File Save Method – Part 2
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
strFileName = saveFileDialog1.FileName;
FileStream flavorsFileOut = new FileStream(strFileName, FileMode.Create);
StreamWriter flavorsStreamWriter = new StreamWriter(flavorsFileOut);
intMaximum = cboCoffee.Items.Count;
for (intIndex = 0; intIndex < intMaximum; intIndex++)
{
flavorsStreamWriter.WriteLine(cboCoffee.Items[intIndex]);
}
flavorsStreamWriter.Close();
cblnIsDataSaved = true; //reset flag after saving data
}
}
catch
{
MessageBox.Show("Error saving the changes to the data file.",
"Error Saving Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} CIS162AD
23
Open for Output (.Create)
FileStream flavorsFileOut = new FileStream(strFileName, FileMode.Create);
Create erases existing data, or creates a new file.
There is an Append option, which adds data to the end
of an existing file.
FileStream flavorsFileOut = new FileStream(strFileName, FileMode.Append);
This may be useful when merging files and the contents
one file is added to the end of another file.
When appending the data, make sure you don’t end up
with duplicate records.
CIS162AD
24
WriteLine Method
flavorsStreamWriter.WriteLine(cboCoffee.Items[intIndex]);
Use WriteLine method to store data to a text file.
WriteLine adds a carriage return and linefeed at
the end of each record.
CIS162AD
25
Close File
flavorsStreamWriter.Close( );
Close releases file to Operating System (OS).
Other users may get file locked error if file is
not closed.
Good housekeeping.
CIS162AD
26
Use Pretest loops to Read Files
Do loops (posttest) do NOT handle empty files.
do
{
strflavorName = flavorsStreamReader.ReadLine( );
recordCount ++;
} while (flavorsStreamReader.Peek != -1);
//recordCount would = one instead of zero for an empty file
Use while (pretest) for file processing.
while (flavorStreamReader.Peek != -1)
{
strflavorName = flavorsStreamReader.ReadLine( );
recordCount ++;
}
//recordCount would = zero for an empty file
CIS162AD
27
ReadLine and EOF
Note that ReadLine does NOT throw an
exception when you attempt to read past the
end of the file.
That is why it is important to use a pretest
loop, so that we can check if we are at the end
of the file before attempting ReadLine.
CIS162AD
28
Summary
Information Processing Cycle
File Processing
CIS162AD
29