How to work with files and data streams

Slides:



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

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.
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.
Understanding Input/Output (I/O) Classes Lesson 5.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Computer and Programming File I/O File Input/Output Author: Chaiporn Jaikaeo, Jittat Fakcharoenphol Edited by Supaporn Erjongmanee Lecture 13.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
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.
Neal Stublen Open/Close Connections  ADO.NET uses “connection pooling” to optimize opening and closing connections to the database.
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
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION.
File I/O 11_file_processing.ppt
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.
Files and Streams File Types, Using Streams, Manipulating Files SoftUni Team Technical Trainers Software University
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
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.
CS360 Windows Programming
Chapter 14: Files and Streams. 2Microsoft Visual C# 2012, Fifth Edition Files and the File and Directory Classes Temporary storage – Usually called computer.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
Chapter 8 Files 1/4/20161Copyright © 2012 Thomas P. Skinner.
Building Your Own Class. We will build a simple instance class for an inventory control application and a main program to test it. We need an Item class.
Input and Output 23: Input and Output
CSC 298 Streams and files.
Ajay Tripathi Input Output. Ajay Tripathi Input/output (IO) refers to the operations for reading and writing data to streams and files. In the.NET Framework,
Introduction to VB programming Dr. John P. Abraham UTPA Chapters 2 & 3.
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 Streams Lec Introduction  Files are used for long-term retention of large amounts of data, even after the program that created the.
Chapter 6: Creating Windows–based Applications 1 Microsoft® Visual C# 2008.
1 Displaying Dialog Boxes Kashef Mughal. 2 Midterm Stats Here we go  Average was  Low was 116  High was 184  Mid Quarter Grade - check any.
INF230 Basics in C# Programming
Module 6: Building .NET–based Applications with C#
Microsoft Visual Basic 2010: Reloaded Fourth Edition
Input and Output 23: Input and Output
The Visual Basic .NET Coach
C# Programming: From Problem Analysis to Program Design
Program Input/Output (I/O)
How to work with indexers, delegates, events, and operators
CHAPTER 5 JAVA FILE INPUT/OUTPUT
File Types, Using Streams, Manipulating Files
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
How to Create and use Classes and Structures
CSCI 3327 Visual Basic Chapter 11: Files and Streams
Files and Streams.
Exception Handling.
C# Programming: From Problem Analysis to Program Design
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
File Input/Output (I/O)
Java for Teachers Intermediate
טיפול בקבצים ליווי מקצועי : ארז קלר
Files & Streams.
Microsoft® Small Basic
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.
Exception Handling.
Files and Streams Lect10 GC201 12/1/2015.
How to work with files and data 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.
Introduction to Programming Lecture 6
Files and Streams.
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

How to work with files and data streams Murach Chapter 21

Objectives Applied Develop an application that requires the use of text or binary files. Knowledge Distinguish between a text file and a binary file. Describe the use of FileStream StreamReader StreamWriter BinaryReader BinaryWriter objects. Describe two common types of I/O exceptions.

Main Sistem.IO File Classes and Operations

System.IO classes used to work with drives and directories Using System.IO; System.IO classes used to work with drives and directories Code that uses some of the Directory methods string dir = @"C:\C# 2015\Files\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Code that uses some of the File methods string path = dir + "Products.txt"; if (File.Exists(path)) File.Delete(path);

Very Common System.IO Methods Exists(path) Delete(path) Copy(source, destination) Move(Source, destination)

A text file displayed in a text editor (.txt) Text and binary files A text file displayed in a text editor (.txt)     A binary file displayed in a text editor (.dat) (ProductMaintenance) public class ProductDB private const string dir = @"C:\C# 2015\Files\"; private const string path = dir + "Products.dat";

Two types of Files and Streams https://en.wikipedia.org/wiki/Binary_file

System.IO classes used to work with files and streams

The syntax for creating a FileStream object

FileShare Enumeration Member name Description Delete Allows subsequent deleting of a file. Inheritable Makes the file handle inheritable by child processes. This is not directly supported by Win32. None Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed. Read Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file. ReadWrite Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file. Write Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

System.IO classes used to work with files and streams

Code that creates a FileStream object for writing string path = @"C:\C# 2015\Files\Products.txt"; FileStream fs = new FileStream( path, FileMode.Create, FileAccess.Write); Code that creates a new FileStream object for reading path, FileMode.Open, FileAccess.Read); string path = @“.\Products.txt "; - will be in bin string path = @"..\..\Products.txt"; - will be next to sources Just because you added a file (e.g. txt) to your solution doesn't mean the file is placed into your output bin/debug directory. If you want to use relative path, make sure your text file is copied during build to the output directory. To do this, in solution explorer go to properties of the text file and set Copy to Output Directory to Always or Copy if newer.

The exception classes for file I/O

Code that uses exception classes string dirPath = @"C:\C# 2015\Files\"; string filePath = dirPath + "Products.txt"; FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open); // code that uses the file stream // to read and write data from the file } catch(FileNotFoundException) MessageBox.Show(filePath + " not found.", "File Not Found"); catch(DirectoryNotFoundException) MessageBox.Show(dirPath + " not found.", "Directory Not Found"); catch(IOException ex) MessageBox.Show(ex.Message, "IOException"); finally if (fs != null) fs.Close();

The basic syntax for creating a StreamWriter object

Code that writes data from a collection of Product objects to a text file StreamWriter textOut = new StreamWriter( new FileStream( path, FileMode.Create, FileAccess.Write));   foreach (Product product in products) { textOut.Write(product.Code + "|"); textOut.Write(product.Description + "|"); //same line as above textOut.WriteLine(product.Price); } textOut.Close();

The basic syntax for creating a StreamReader object

Code that reads data from a text file into a collection of Product objects StreamReader textIn = new StreamReader( new FileStream( path, FileMode.OpenOrCreate, FileAccess.Read));   List<Product> products = new List<Product>(); while (textIn.Peek() != -1) { string row = textIn.ReadLine(); string[] columns = row.Split('|'); Product product = new Product(); product.Code = columns[0]; product.Description = columns[1]; product.Price = Convert.ToDecimal(columns[2]); products.Add(product); } textIn.Close();

Again

A class that works with a text file using System; using System.IO; using System.Collections.Generic; namespace ProductMaintenance { public static class ProductDB private const string dir = @"C:\C# 2015\Files\"; private const string path = dir + "Products.txt"; public static List<Product> GetProducts() // if the directory doesn't exist, create it if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // create the object for the input stream for a text file StreamReader textIn = new StreamReader( new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

A class that works with a text file cont. // create the list List<Product> products = new List<Product>(); // read the data from the file and store it in the list while (textIn.Peek() != -1) { string row = textIn.ReadLine(); string[] columns = row.Split('|'); Product product = new Product(); product.Code = columns[0]; product.Description = columns[1]; product.Price = Convert.ToDecimal(columns[2]); products.Add(product); } // close the input stream for the text file textIn.Close(); return products;

A class that works with a text file (Save) cont. public static void SaveProducts(List<Product> products) { // create the output stream for a text file that exists StreamWriter textOut = new StreamWriter( new FileStream(path, FileMode.Create, FileAccess.Write)); // write each product foreach (Product product in products) textOut.Write(product.Code + "|"); textOut.Write(product.Description + "|"); textOut.WriteLine(product.Price); } // close the output stream for the text file textOut.Close();

The basic syntax for creating a BinaryWriter object

The basic syntax for creating a BinaryWriter object cont

Code that writes data from a collection of Product objects to a binary file BinaryWriter binaryOut = new BinaryWriter( new FileStream(path, FileMode.Create, FileAccess.Write));   foreach (Product product in products) { binaryOut.Write(product.Code); binaryOut.Write(product.Description); binaryOut.Write(product.Price); } binaryOut.Close();

The basic syntax for creating a BinaryReader object

Code that reads data from a binary file into a collection of Product objects BinaryReader binaryIn = new BinaryReader( new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));   List<Product> products = new List<Product>(); while (binaryIn.PeekChar() != -1) { Product product = new Product(); product.Code = binaryIn.ReadString(); product.Description = binaryIn.ReadString(); product.Price = binaryIn.ReadDecimal(); products.Add(product); } binaryIn.Close();

A class that works with a binary file public class ProductDB { private const string dir = @"C:\C# 2015\Files\"; private const string path = dir + "Products.dat"; public static List<Product> GetProducts() // if the directory doesn't exist, create it if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // create the object for the input stream for a binary file BinaryReader binaryIn = new BinaryReader( new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

A class that works with a binary file cont // create the array list List<Product> products = new List<Product>(); // read the data from the file and store it in the List<Product> while (binaryIn.PeekChar() != -1) { Product product = new Product(); product.Code = binaryIn.ReadString(); product.Description = binaryIn.ReadString(); product.Price = binaryIn.ReadDecimal(); products.Add(product); } // close the input stream for the binary file binaryIn.Close(); return products;

A class that works with a binary file cont public static void SaveProducts(List<Product> products) { // create the output stream for a binary file that exists BinaryWriter binaryOut = new BinaryWriter( new FileStream(path, FileMode.Create, FileAccess.Write)); // write each product foreach (Product product in products) binaryOut.Write(product.Code); binaryOut.Write(product.Description); binaryOut.Write(product.Price); } // close the output stream binaryOut.Close();

Project 5-1 Maintain student scores (text file)