C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.

Slides:



Advertisements
Similar presentations
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Copyright © 2012 Pearson Education, Inc. Chapter 11 MORE WINDOWS CONTROLS & STANDARD DIALOG BOXES.
Object Oriented Programming Files and Streams Dr. Mike Spann
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 Classes.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 SKIPPED.
Using Multiple Forms. Creating a New Form ProjectAdd Windows Form.
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13.
File and Streams There are many ways of organizing records in a file. There are many ways of organizing records in a file. The most common type of organization.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
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.
Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda.
Chapter 9 Files I/O: Files, Records and Fields Part 3.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
File I/O 11_file_processing.ppt
 2006 Pearson Education, Inc. All rights reserved Files and Streams.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
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.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 Classes.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
Files and Streams Chapter What You Will Learn Create files Read files Write files Update files.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing.
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.  persistent data.  The smallest.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message).
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Object Serialization. Sequential-access Text Files Sequential-access files store records In order by the record-key field Java imposes no structure on.
CSC 298 Streams and files.
Chapter 21 – Files and Streams 1 Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
INF230 Basics in C# Programming
3 Introduction to Classes and Objects.
C# Programming: From Problem Analysis to Program Design
18 Files and Streams.
Using Multiple Forms.
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
CSCI 3327 Visual Basic Chapter 11: Files and Streams
Files and Streams.
Files and Streams Lect3 CT1411.
Chapter 17 – Files and Streams
Topics Introduction to File Input and Output
Files & Streams.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams UTPA – Fall 2012 This set of slides is revised from lecture slides of Prof.
Files and Streams.
Topics Introduction to File Input and Output
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access File

Files and Streams When file opened C#: Creates an object Associates a stream with that object Three stream objects: Console.In: returns standard input stream object Console.Out: returns standard output stream object Console.Error: returns standard error stream object Namespace System.IO needed for file processing

Files and Streams System.IO.Stream: allows representation of stream as bits FileStream: read to and write from sequential- access and random-access files MemoryStream:transfer of data directly to and from memory BufferedStream: uses buffer to transfer to memory

Classes File and Directory Information stored in files Files organized in directories Directory class used to manipulate directories File class used to manipulate files Only has static methods, cannot instantiate File objects

// get user-specified file or directory string fileName = ??? // determine whether fileName is a file if ( File.Exists( fileName ) ) { // obtain reader and file contents try { StreamReader stream = new StreamReader( fileName ); string inputString = stream.ReadToEnd(); } // handle exception if StreamReader is unavailable catch( IOException ) { MessageBox.Show( "File Error", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); Set fileName to what user typed See if fileName is an existing file Create StreamReader to read text from file Call method ReadToEnd

else { // notify user that neither file nor directory exists MessageBox.Show( filename + " does not exist", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } // end if FileTest.cs If user input is not existing file output error message

SaveFileDialog

SaveFileDialog fileChooser = new SaveFileDialog(); // create dialog box enabling user to save file SaveFileDialog fileChooser = new SaveFileDialog(); DialogResult result = fileChooser.ShowDialog(); // allow user to create file fileChooser.CheckFileExists = false; // exit event handler if user clicked "Cancel“ if ( result != DialogResult.Cancel ) { // get specified file name string fileName = fileChooser.FileName; // show error if user specified invalid file if ( fileName == "" || fileName == null ) MessageBox.Show( "Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); Instantiate SaveFileDialog object Show SaveFileDialog Test if user canceled save Get file name to save to

// save file via FileStream if user specified valid file try else { // save file via FileStream if user specified valid file try // open file with write access output = new FileStream( fileName, FileMode.OpenOrCreate, FileAccess.Write ); } // notify user if file does not exist catch ( FileNotFoundException ) MessageBox.Show( "File Does Not Exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); Instantiate output stream with write permission Method to save data when user clicks enter

Creating or Writing to a Sequential-Access File Programmers have to structure files to meet the requirements of applications Declare and define a record class which describes the structure of the data Write the main class to write out a record

Libraries Needed to read a file sequentially using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization;

// set members to default values [Serializable] public class Record { private int account; private string firstName; private string lastName; private double balance; // set members to default values public Record() : this( 0, "", "", 0.0 ) { } Tells compiler objects of class Record can be represented as a set of bytes Data to go into record Sets members to 0

// set members to parameter values public Record( int accountValue, string firstNameValue, string lastNameValue, double balanceValue ) { Account = accountValue; FirstName = firstNameValue; LastName = lastNameValue; Balance = balanceValue; } // end constructor Set members to parameters

Record.cs // property Account public int Account { get { return account; } set { account = value; } } // end property Account } //end class Record.cs Other properties and methods

Main class // Creating a sequential-access file of records // C# namespaces using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; // serializes Record in binary format private BinaryFormatter formatter = new BinaryFormatter(); // stream through which serializable data is written to file private FileStream output;

formatter.Serialize( output, record ); // Record containing TextBox values to serialize Record record = new Record(); // store values in Record and serialize Record try { record.Account = Int32.Parse( values[ ( int )TextBoxIndices.ACCOUNT ] ); record.FirstName = values[ ( int )TextBoxIndices.FIRST ]; record.LastName = values[ ( int )TextBoxIndices.LAST ]; record.Balance = Double.Parse( values[ ( int )TextBoxIndices.BALANCE ] ); // write Record to FileStream (serialize object) formatter.Serialize( output, record ); } Store TextBox fields in record Write data to file

// notify user if error occurs in serialization catch( SerializationException ) { MessageBox.Show( "Error Writing to File", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } // notify user if error occurs regarding parameter format catch( FormatException ) MessageBox.Show( "Invalid Format", "Error", Catch block if user input invalid data Close FileStream

Don’t forget to close the output file! // invoked when user clicks Exit button private void exitButton_Click( object sender, System.EventArgs e ) { // determine whether file exists if ( output != null ) // close file try output.Close(); }

Reading Data from a Sequential-Access File Read data sequentially from a file Programs usually start at beginning of file and read data consecutively until the desired data is found Sometimes necessary to do this several times during execution of a program File-position pointer: Points to next byte to be read from or written to file Can be repositioned to any point in file

private void openButton_Click( object sender, System.EventArgs e ) { // invoked when user clicks Open File button private void openButton_Click( object sender, System.EventArgs e ) { // create dialog box enabling user to open file OpenFileDialog fileChooser = new OpenFileDialog(); DialogResult result = fileChooser.ShowDialog(); // exit event handler if user clicked Cancel if ( result != DialogResult.Cancel ) { // get name from user fileName = fileChooser.FileName; // show error if user specified invalid file if ( fileName == "" || fileName == null ) MessageBox.Show( "Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); User clicked open button Instantiate OpenFileDialog Show OpenFileDialog

87 88 // read and display file information 89 try 90 { 91 // close file from previous operation 92 if ( input != null ) 93 input.Close(); 94 95 // create FileStream to obtain read access to file 96 input = new FileStream( fileName, FileMode.Open, FileAccess.Read );

101 // traverse file until end of file 102 while ( true ) 103 { 103 { 104 // get next Record available in file Record record = ( Record )reader.Deserialize( input ); // display record 114 string output = record.Account + "\t" + 115 record.FirstName + "\t" + record.LastName + 116 new string( ' ', 6 ) + "\t"; 117 118 // display balance with correct monetary format 119 output += String.Format( 120 "{0:F}", balance ) + "\r\n"; 121 122 // copy output to screen 123 displayTextBox.Text += output; 124 } While loop to read from file Read input from file

// handle exception when no more records { catch( SerializationException ) { // close FileStream if no Records in file input.Close(); } No more records exception Close FileStream