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

Slides:



Advertisements
Similar presentations
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Advertisements

Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
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.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
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.
CIS 270—Application Development II Chapter 14—Files and Streams.
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
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
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.
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.
CS360 Windows Programming
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Chapter 14: Files and Streams. 2Microsoft Visual C# 2012, Fifth Edition Files and the File and Directory Classes Temporary storage – Usually called computer.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
 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).
LINQ AND GENERIC COLLECTIONS DR. JOHN P. ABRAHAM PROFESSOR UTPA.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 15.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
Input and Output 23: Input and Output
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.
CSCI 3328 Object Oriented Programming in C# Chapter 12: Databases and LINQ – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Files and Streams Lec Introduction  Files are used for long-term retention of large amounts of data, even after the program that created the.
Input and Output 23: Input and Output
TMF1414 Introduction to Programming
CSCI 3327 Visual Basic Chapter 11: Files and Streams
Files.
18 Files and Streams.
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.
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
Reading and Writing Files
Files & Streams.
The University of Texas – Pan American
CSCI 3327 Visual Basic Review: Final Exam
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections UTPA – Fall 2012 This set of slides is revised from lecture slides.
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises UTPA – Fall 2012 This set of slides is revised from lecture slides.
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
Object Oriented Programming
Files and Streams Lect10 GC201 12/1/2015.
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
Fundaments of Game Design
BO65: PROGRAMMING WRITING TO TEXT FILES.
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.
Presentation transcript:

CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX

Objectives In this chapter, you will –Learn how to create, read, write, and update files –Know how to use classes File and Directory to obtain information about files and directories on your computer –Learn how to use LINQ to search through directories –Get familiar with sequential-access file processing –Know how to use classes FileStream, StreamReader, StreamWriter, FileStream, and BinaryFormatter, as well as yield return 2

Introduction Variables and arrays only offer temporary storage of data –Data are lost when the program terminates In contrast, files are used for long-term storage place –Persistent data –Data are stored on secondary storage devices 3

Data Hierarchy Bits Characters (ASCII or Unicode) Fields Records Files –Record key –Sequential file Databases 4

Files and Streams File as a sequential stream of bytes Each file ends with an end-of-file marker Windows keeps track of total number of bytes in a file When a file is opened an object is created and a stream is associated with the object Each program automatically gets 3 objects, Console.Out, Console.In and Console.Error 5

Classes File and Directory Files are organized in directories Class Directory provides capabilities for manipulating directories Class File has static methods: –AppendText, Copy, Create, CreateText, Delete, Exists, GetCreationTime, GetLastAccessTime, GetLastWriteTime, Move, Open, OpenRead, OpenText, OpenWrite 6

Directory Class Static Methods CreateDirectory Delete Exists GetDirectories GetFiles GetCreationTime GetLastAccessTime GetLastWriteTime Move 7

Create a File to Read/Write Pre-defined class library –using System.IO; StreamWriter (for text output) –StreamWriter outFile = new StreamWriter(fileName); StreamReader (for text input) –StreamReader inFile = null; try{ using (inFile = new StreamReader(fileName)) { outputTextBox.AppendText(inFile.ReadToEnd());} } catch(IOException) { MessageBox.Show("Error reading from file", "File Error", MessageBoxButton.OK, MessageBoxIcon.Error); } 8

Write to the File string fileName="test.txt"; File.Exists(fileName) –true, if fileName exists outFile.WriteLine("text"); Other methods –File.GetCreationTime(fileName); –File.GetLastWriteTime(fileName); –File.GetLastAccessTime(fileName); 9

Read From the File inFile.ReadLine(); 10

Close the File outFile.Close(); inFile.Close(); 11

Directory Directory.Exists(Name); –true, if directory Name exists string [] directoryList = Directory.GetDirectories(Name); –Obtain a list of files and directories 12

Searching Directories with LINQ string currentDirectory; currentDirectory = Directory.GetCurrentDirectory(); string [] files = Directory.GetFiles(currentDirectory); string [] directories=Directory.GetDirectories(currentDirectory); var extensions = (from file in files select Path.GetExtension(file)).Distinct(); foreach(var extension in extensions) { var extensionCount = (from file in files where Path.GetExtension(file)==extension select file).Count(); } 13

Dictionary Class A class Dictionary is a collection of key/value pairs –In namespace System.Collections.Generic –Dictionary found = new Dictionary (); Key is of string data type, and value is of int data type Methods –found.ContainsKey(extension) true, if the directory contains a key for the extension –found.Add(extension, extensionCount); –found[extension] Returns the value of the key "extension" –found.Keys A collection of keys 14

Example of Deleting Files var backupFiles = from file in files where Path.GetExtension(file)==".bak" select file; foreach (var backup in backupFiles) { DialogResult result = MessageBox.Show("Found backup file " + Path.GetFileName(backup) + ". Delete?", "Delete Backup", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { File.Delete(backup);// delete the file with name in "backup" found[".bak"]--;// decrement the counter if (found[".bak"] == 0) found.Remove(".bak");// remove the key from dictionary } 15

Create a Sequential File In C# files, the concept of a "record" does not exist Therefore, you have to create structured files by yourself –Use text and special characters to separate fields in the record 16

Example of Creating a Sequential File public class Record { public int Account {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public decimal Balance {get; set;} public Record() :this(0, string.Empty, string.Empty, 0M){} public RecordSerializable (int acc, string fName, string lName, decimal bal) { Account = acc; FirstName = fName; LastName = lName; Balance = bal; } 17

Example of Creating a Sequential File (cont'd) FileStream output = new FileStream (fileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter fileWriter = new StreamWriter(output); Record record = new Record(); fileWriter.WriteLine(record.Account + "," + record.FirstName + "," + record.LastName + "," + record.Balance); 18

Reading Data From a Sequential- Access Text File FileStream input = new FileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader fileReader = new StreamReader(input); string inputRecord = fileReader.ReadLine(); string[] inputFields; if (inputRecord != null) { inputFields = inputRecord.Split(','); Record record = new Record(Convert.ToInt32(inputFields[0]), inputFields[1], inputFields[2], Convert.ToDecimal(inputFields[3])); } 19

Class BinaryFormatter –Under namespace System.Runtime.Serialization.Formatters.Binary –Serializable(outFile, object) method Write a serializable object to the output file Serialization –In a class that is marked with [Serializable] attribute or that implements interface Iserializable, you must ensure that every instance variable in a class is also serializable –All simple-type variables, strings, and arrays (without containing references) are serializable 20

Example of RecordSerializable Class public class RecordSerializable { [Serializable] public int Account {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public decimal Balance {get; set;} public RecordSerializable() :this(0, string.Empty, string.Empty, 0M){} public RecordSerializable (int acc, string fName, string lName, decimal bal) { Account = acc; FirstName = fName; LastName = lName; Balance = bal; } 21

Example of RecordSerializable Class (cont'd) BinaryFormatter formatter = new BinaryFormatter(); FileStream output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); try{ RecordSerializable record = new RecordSerializable(); formatter.Serialize(output, record); } catch (SerializationException) { // … } catch (FormatException) { // … } 22

Reading and Deserializing Data From a Binary File BinaryFormatter reader = new BinaryFormatter(); FileStream input = new FileStream(fileName, FileMode.Open, FileAccess.Read); try{ RecordSerializable record = (RecordSerializable) reader.Deserialize(input); } catch (SerializationException) { input.Close(); } 23

Select Files from Chooser Recall this topic in lecture slides of Chapter 8 24

Obtaining File Name From Chooser OpenFileDialog fDialog = new OpenFileDialog(); if (fDialog.ShowDialog() == DialogResult.OK) { fileName = (fDialog.FileName.ToString()); MessageBox.Show(fileName); } 25

Reading From a File StreamReader ofile = new StreamReader(fileName); while (ofile.Peek()!=-1) { string oneline = ofile.ReadLine(); MessageBox.Show(oneline,"Reading From File.."); string[] items = oneline.Split(','); onePerson.fName = items[0]; onePerson.lName = items[1]; onePerson.GPA = Convert.ToSingle(items[3]); onePerson.Tele = items[2]; friendsList.Add(onePerson); } ofile.Close(); 26

Writing to the File StreamWriter outfile = new StreamWriter(fileName); foreach (Info person in friendsList) outfile.WriteLine(person.fName+","+person.lName+","+person.Tele+","+Convert.ToString(person.GPA)); outfile.Close(); 27

28