CSCI 3328 Object Oriented Programming in C Chapter

CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539 xiang. lian@utrgv. edu 1

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 File. Stream, Stream. Reader, Stream. Writer, File. Stream, and Binary. Formatter, 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: – Append. Text, Copy, Create. Text, Delete, Exists, Get. Creation. Time, Get. Last. Access. Time, Get. Last. Write. Time, Move, Open. Read, Open. Text, Open. Write 6

Directory Class Static Methods • • • Create. Directory Delete Exists Get. Directories Get. Files Get. Creation. Time Get. Last. Access. Time Get. Last. Write. Time Move 7

Create a File to Read/Write • Pre-defined class library – using System. IO; • Stream. Writer (for text output) – Stream. Writer out. File = new Stream. Writer(file. Name); • Stream. Reader (for text input) – Stream. Reader in. File = null; try{ using (in. File = new Stream. Reader(file. Name)) { output. Text. Box. Append. Text(in. File. Read. To. End()); } } catch(IOException) { Message. Box. Show("Error reading from file", "File Error", Message. Box. Button. OK, Message. Box. Icon. Error); } 8

Write to the File • string file. Name="test. txt"; • File. Exists(file. Name) – true, if file. Name exists • out. File. Write. Line("text"); • Other methods – File. Get. Creation. Time(file. Name); – File. Get. Last. Write. Time(file. Name); – File. Get. Last. Access. Time(file. Name); 9

Read From the File • in. File. Read. Line(); 10

Close the File • out. File. Close(); • in. File. Close(); 11
![Directory • Directory. Exists(Name); – true, if directory Name exists • string [] directory. Directory • Directory. Exists(Name); – true, if directory Name exists • string [] directory.](http://slidetodoc.com/presentation_image_h2/6826a439d0054a333e4934d9c184af24/image-12.jpg)
Directory • Directory. Exists(Name); – true, if directory Name exists • string [] directory. List = Directory. Get. Directories(Name); – Obtain a list of files and directories 12

Searching Directories with LINQ • • • string current. Directory; current. Directory = Directory. Get. Current. Directory(); string [] files = Directory. Get. Files(current. Directory); string [] directories=Directory. Get. Directories(current. Directory); var extensions = (from file in files select Path. Get. Extension(file)). Distinct(); foreach(var extension in extensions) { var extension. Count = (from file in files where Path. Get. Extension(file)==extension select file). Count(); } 13

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

Example of Deleting Files var backup. Files = from file in files where Path. Get. Extension(file)==". bak" select file; foreach (var backup in backup. Files) { Dialog. Result result = Message. Box. Show("Found backup file " + Path. Get. File. Name(backup) + ". Delete? ", "Delete Backup", Message. Box. Buttons. Yes. No, Message. Box. Icon. Question); if (result == Dialog. Result. Yes) { File. Delete(backup); found[". bak"]--; if (found[". bak"] == 0) found. Remove(". bak"); } // delete the file with name in "backup" // decrement the counter // 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 First. Name {get; set; } public string Last. Name {get; set; } public decimal Balance {get; set; } public Record() : this(0, string. Empty, 0 M){} public Record. Serializable (int acc, string f. Name, string l. Name, decimal bal) { Account = acc; First. Name = f. Name; Last. Name = l. Name; Balance = bal; } } 17

Example of Creating a Sequential File (cont'd) • File. Stream output = new File. Stream (file. Name, File. Mode. Open. Or. Create, File. Access. Write); • Stream. Writer file. Writer = new Stream. Writer(output); • Record record = new Record(); • file. Writer. Write. Line(record. Account + ", " + record. First. Name + ", " + record. Last. Name + ", " + record. Balance); 18

Reading Data From a Sequential. Access Text File • File. Stream input = new File. Stream(file. Name, File. Mode. Open, File. Access. Read); • Stream. Reader file. Reader = new Stream. Reader(input); • string input. Record = file. Reader. Read. Line(); • string[] input. Fields; • if (input. Record != null) { input. Fields = input. Record. Split(', '); Record record = new Record(Convert. To. Int 32(input. Fields[0]), input. Fields[1], input. Fields[2], Convert. To. Decimal(input. Fields[3])); } 19

Class Binary. Formatter • Class Binary. Formatter – Under namespace System. Runtime. Serialization. Formatters. Binary – Serializable(out. File, 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 Record. Serializable Class public class Record. Serializable { [Serializable] public int Account Example of Record. Serializable Class public class Record. Serializable { [Serializable] public int Account](http://slidetodoc.com/presentation_image_h2/6826a439d0054a333e4934d9c184af24/image-21.jpg)
Example of Record. Serializable Class public class Record. Serializable { [Serializable] public int Account {get; set; } public string First. Name {get; set; } public string Last. Name {get; set; } public decimal Balance {get; set; } public Record. Serializable() : this(0, string. Empty, 0 M){} public Record. Serializable (int acc, string f. Name, string l. Name, decimal bal) { Account = acc; First. Name = f. Name; Last. Name = l. Name; Balance = bal; } } 21

Example of Record. Serializable Class (cont'd) Binary. Formatter formatter = new Binary. Formatter(); File. Stream output = new File. Stream(file. Name, File. Access. Write); File. Mode. Open. Or. Create, try{ Record. Serializable record = new Record. Serializable(); formatter. Serialize(output, record); } catch (Serialization. Exception) { // … } catch (Format. Exception) { // … } 22

Reading and Deserializing Data From a Binary File Binary. Formatter reader = new Binary. Formatter(); File. Stream input = new File. Stream(file. Name, File. Mode. Open, File. Access. Read); try{ Record. Serializable record = (Record. Serializable) reader. Deserialize(input); } catch (Serialization. Exception) { input. Close(); } 23

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

Obtaining File Name From Chooser Open. File. Dialog f. Dialog = new Open. File. Dialog(); if (f. Dialog. Show. Dialog() == Dialog. Result. OK) { file. Name = (f. Dialog. File. Name. To. String()); Message. Box. Show(file. Name); } 25

Reading From a File Stream. Reader ofile = new Stream. Reader(file. Name); while (ofile. Peek()!=-1) { string oneline = ofile. Read. Line(); Message. Box. Show(oneline, "Reading From File. . "); string[] items = oneline. Split(', '); one. Person. f. Name = items[0]; one. Person. l. Name = items[1]; one. Person. GPA = Convert. To. Single(items[3]); one. Person. Tele = items[2]; friends. List. Add(one. Person); } ofile. Close(); 26

Writing to the File Stream. Writer outfile = new Stream. Writer(file. Name); foreach (Info person in friends. List) outfile. Write. Line(person. f. Name+", "+person. l. Name+ ", "+person. Tele+", "+Convert. To. String(person. GPA)); outfile. Close(); 27

28
- Slides: 28