Upload
paulina-banks
View
242
Download
1
Embed Size (px)
Citation preview
CIS162AD - C#
File I/O
11_file_processing.ppt
CIS162AD 2
Overview of Topics
Information Processing Cycle File Processing (I/O)
CIS162AD 3
Hardware Model
Input Devices Memory (RAM) Output Devices
CPU
Storage DevicesTo this point we have been using the text boxes for input and picture boxes for output. Both of these are temporary.
CIS162AD 4
Information Processing Cycle
InputRaw Data
Process (Application)
OutputInformation
StorageOutput from one process can serve as input to another process.
Storage is referred to as secondary storage, and it is permanent storage. Data is permanently stored in files.
CIS162AD 5
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 6
CS11 Assignment
We have a file named catalogs.txt The file has 7 catalog names as separate records. To process the file:
– open file.– read a catalog name and load it into the combo box.– need a loop to read and load each record.– allow users to add and remove catalog names. – and then save the results back to catalogs.txt.
Sequential file Processing – processing the records in the order they are stored in the file.
CIS162AD 7
catalogs.txtOdds and EndsSolutionsCamping NeedsToolTimeSpiegelThe Outlet
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 the last one. The file should be saved in the Debug folder
within the bin folder of the project folder. CS11 > bin > Debug > catalogs.txt
CIS162AD 8
Sample Interface - same as CS10
CIS162AD 9
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.
Use the using command at the top of program before the form declaration to include the class definitions.
using System.IO;
namespace CS11 { public partial class CS11Form : Form {
CIS162AD 10
Form Load Event The form load event is triggered when a form is first
loaded. In the method that captures this event, we can add
code to initialize or load data that should be available when the form is displayed.
We will place the code to load the catalog names from the file into the items collection of the combo box in the form load event method.
CIS162AD 11
Load Data Procedureprivate void CS11Form_Load(object sender, EventArgs e){
string strCatalogName; try
{ FileStream catalogFileIn = new FileStream("Catalogs.txt", FileMode.Open); //Define file StreamReader catalogStreamReader = new StreamReader(catalogFileIn); //Open file
while (catalogStreamReader..Peek() != -1) //Test for EOF {
strCatalogName = catalogStreamReader.ReadLine( ); //Read record catalogComboBox.Items.Add(strCatalogName); //Add catalog name } catalogStreamReader.Close( ); //Close file
} catch{ DialogResult responseDialogResult;
responseDialogResult = MessageBox.Show("File does not exist. Do you wish to create it?",
"File Not Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (responseDialogResult != DialogResult.Yes) this.Close( ); //End the program } }
CIS162AD 12
Internal and External File Names catalogs.txt is the external file name. catalogFileIn is the internal file name. FileStream catalogFileIn = new FileStream("Catalogs.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. The default folder is the same folder that executable is saved in
(Debug folder inside of bin folder). A directory path can be included as part of the external filename.
CIS162AD 13
Use Try/Catch When Opening Filestry{ FileStream catalogFileIn = new FileStream("Catalogs.txt", FileMode.Open); //Define file StreamReader catalogStreamReader = new StreamReader(catalogFileIn); //Open file
while (catalogStreamReader..Peek() != -1) //Test for EOF {
strCatalogName = catalogStreamReader.ReadLine( ); //Read record catalogComboBox.Items.Add(strCatalogName); //Add catalog name }
catalogStreamReader.Close( ); //Close file} catch{
DialogResult responseDialogResult; responseDialogResult = MessageBox.Show("File does not exist. Do you wish to create it?",
"File Not Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (responseDialogResult != DialogResult.Yes) this.Close( ); //End the program }
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 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, 0 or 1
– Y or N, 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.
while (catalogStreamReader.Peek( ) != -1)
CIS162AD 16
Close File
catalogStreamReader.Close( );
Close releases file to Operating System (OS). Other users may get file locked error if file is
not closed. Good housekeeping.
CIS162AD 17
blnIsDataSaved 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 blnIsDataSaved 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 Procedure private void mnuFileExit_Click( … )
{ //blnIsDataSaved checked in Form Closing event procedure. this.Close( );}
private void CS11Form_FormClosing( … ) { DialogResult dgrResponse;
if (blnIsDataSaved = = 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
File Save Method
private void mnuFileSave_Click(object sender, EventArgs e ){ int intIndex, intMaximum; try { FileStream catalogFileOut = new FileStream("Catalogs.txt", FileMode.Create); StreamWriter catalogStreamWriter = new StreamWriter(catalogFileOut);
intMaximum = cboCatalog.Items.Count; for (intIndex = 0; intIndex < intMaximum; intIndex++) {
catalogStreamWriter.WriteLine(cboCatalog.Items[intIndex]); }
catalogStreamWriter.Close( ); blnIsDataSaved = true: } catch { MessageBox.Show("Error saving the changes to the data file.", "Error Saving Data", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
CIS162AD 21
Open for Output (.Create) FileStream catalogFileOut = new FileStream("Catalogs.txt", FileMode.Create); StreamWriter catalogStreamWriter = new StreamWriter(catalogFileOut);
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 catalogFileOut = new FileStream("Catalogs.txt", FileMode.Append);
In CS11 we want to create an new file each time because the entire list is saved. If we append the data, we will end up with duplicate records.
CIS162AD 22
WriteLine Method
catalogStreamWriter.WriteLine(cboCatalog.Items[intIndex]);
Use WriteLine method to store data to a file. WriteLine adds a carriage return and linefeed at
the end of each record.
CIS162AD 23
Close File
catalogStreamWriter.Close( );
Close releases file to Operating System (OS). Other users may get file locked error if file is
not closed. Good housekeeping.
CIS162AD 24
Posttests and Reading Files Do loops (posttest) do NOT handle empty files.
do{
strCatalogName = catalogStreamReader.ReadLine( );recordCount ++;
} while (catalogStreamReader.Peek != -1);
//recordCount would = one instead of zero for an empty file
Use while (pretest) for file processing. while (catalogStreamReader.Peek != -1) { strCatalogName = catalogStreamReader.ReadLine( );
recordCount ++; }
//recordCount would = zero for an empty file
CIS162AD 25
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 26
Summary
Information Processing Cycle File Processing Some code for CS11 was revealed .