File I/O 11_file_processing.ppt

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Alford Academy Business Education and Computing1 Advanced Higher Computing Based on Heriot-Watt University Scholar Materials File Handling.
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Lecture Roger Sutton CO331 Visual Programming 19: Simple file i/o Exceptions – Error handling 1.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
CHAPTER SIX Loop Structures.
Copyright 2007, Information Builders. Slide 1 Maintain & JavaScript: Two Great Tools that Work Great Together Mark Derwin and Mark Rawls Information Builders.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Visual C Sharp – File I/O - 1 Variables and arrays only temporary - lost when a program terminates Files used for long term storage (Data bases considered.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
 What are the different types of loops? ◦ Do….While  Performs statements within loop while a condition is true ◦ Do….Until  Performs statements within.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
With Windows 7 Introductory© 2011 Pearson Education, Inc. Publishing as Prentice Hall1 Windows 7 Introductory Chapter 2 Managing Libraries Folders, Files.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Copyright © 2001 by Wiley. All rights reserved. Chapter 5: The Repetition Process in Visual Basic Event Driven Loops Determinate Loops Indeterminate Loops.
The Repetition Process in Visual Basic. The Repetition Process The capability to repeat one or more statements as many times as necessary is what really.
5-1 Chapter 5 The Repetition Process in VB.NET. 5-2 Learning Objectives Understand the importance of the repetition process in programming. Describe the.
Chapter 10: Structures and Sequential Access Files
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Active-HDL Interfaces Debugging C Code Course 10.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
BIL528 – Bilgisayar Programlama II Introduction 1.
Chapter 9 I/O Streams and Data Files
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
Decisions and Debugging Part06dbg --- if/else, switch, validating data, and enhanced MessageBoxes.
Using Microsoft Visual Studio 2005 Original by Suma Rao Revised by John G. McMahon ( 9/6/2008 )
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 8 Debugging, Creating Executable Files, and Distributing a Windows Application.
C# GUI - Basics. Objectives.NET supports two types: WinForms, traditional, desktop GUI apps. WebForms – newer, for Web apps. Visual Studio.NET supports.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
1.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Ten Structures and Sequential Access Files.
Introduction to Files in VB Chapter 9.1, 9.3. Overview u Data Files  random access  sequential u Working with sequential files  open, read, write,
Copyright (c) 2003 by Prentice Hall Provided By: Qasim Al-ajmi Chapter 2 Introduction to Visual Basic Programming Visual Basic.NET.
1 Windows Forms II Chapter RadioButton / GroupBox Controls Used to solicit a multiple choice input. Radio buttons work as a group. Selecting one.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Chapter 7 Multiple Forms, Modules, and Menus. Section 7.2 MODULES A module contains code—declarations and procedures—that are used by other files in a.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Chapter 14: Sequential Access Files
Topic: File Input/Output (I/O)
An Introduction to Computers and Visual Basic
Files.
An Introduction to Computers and Visual Basic
Files and Streams Lect3 CT1411.
File Input/Output (I/O)
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
CIS16 Application Development and Programming using Visual Basic.net
Text / Serial / Sequential Files
An Introduction to Computers and Visual Basic
CIS16 Application Development and Programming using Visual Basic.net
Topics Introduction to File Input and Output
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

File I/O 11_file_processing.ppt CIS162AD - C# File I/O 11_file_processing.ppt

Overview of Topics Information Processing Cycle File Processing (I/O) CIS162AD

Hardware Model CPU Input Devices Memory (RAM) Output Devices Storage Devices To this point we have been using the text boxes for input and picture boxes for output. Both of these are temporary. CIS162AD

Information Processing Cycle Input Raw Data Process (Application) Output Information Storage Output 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

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

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

catalogs.txt Odds and Ends Solutions Camping Needs ToolTime Spiegel The 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

Sample Interface - same as CS10 CIS162AD

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

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

Load Data Procedure private 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

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

Use Try/Catch When Opening Files 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 Some possible errors: File not found Protection violation on network Disk Full CIS162AD

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

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

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

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

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

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

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

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

WriteLine Method Use WriteLine method to store data to a file. 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

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

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

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

Summary Information Processing Cycle File Processing Some code for CS11 was revealed . CIS162AD