How to work with files and data streams

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

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.
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CHAPTER 6 FILE PROCESSING. 2 Introduction  The most convenient way to process involving large data sets is to store them into a file for later processing.
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.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Understanding Input/Output (I/O) Classes Lesson 5.
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.
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.
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.
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.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Object Oriented Software Development 10. Persistent Storage.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
Files Tutor: You will need ….
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,
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
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.
Chapter 14: Sequential Access Files
INF230 Basics in C# Programming
Module 6: Building .NET–based Applications with C#
Chapter 7 Text Input/Output Objectives
Input and Output 23: Input and Output
C# Programming: From Problem Analysis to Program Design
Program Input/Output (I/O)
Chapter 7 Text Input/Output Objectives
18 Files and Streams.
How to design a Windows Forms application
Creating and Modifying Text part 2
File Types, Using Streams, Manipulating Files
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
How to work with files and data 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)
Topics Introduction to File Input and Output
File IO and Strings CIS 40 – Introduction to Programming in Python
Exception Handling.
Files & Streams.
Fundamentals of Data Structures
Microsoft® Small Basic
File Input and Output.
Exception Handling.
Files and Streams Lect10 GC201 12/1/2015.
Files and Streams.
Topics Introduction to File Input and Output
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 System.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

Files An input file is a file that is read by a program; an output file is a file that is written by a program. Input and output operations are often referred to as I/0 operations or file I/O. A stream is the flow of data from one location to another. To write data, you use an output stream. To read data, you use an input stream. A single stream can also be used for both input and output. To read and write text files, you use text streams. To read and write binary files, youuse binary Streams.

System.IO classes used to work with files and streams

The syntax for creating a FileStream object

Streams new FileStream(path, mode[, access [, share] ]) To create a stream that connects to a file, you use the FileStream class. new FileStream(path, mode[, access [, share] ]) Arguments: the first two, which specify the path for the file and the mode in which it will be opened, are required. The last two, which specify how the file can be accessed and shared, are optional. To code the mode, access, and share arguments, you use the FileMode, FileAccess, and FileShare enumerations. If, for example, you want to create a filestream for a file that doesn’t exist, you can code the FileMode. Create member for the mode argument and a new file will be created. However, this member causes the file to be overwritten if it already exists. As a result, if you don’t want an existing file to be overwritten, you can code the FileMode. CreateNew member for this argument. Then, if the file already exists, an exception is thrown asexplained in the next figure. For the access argument, you can code members that let you read recordsfrom the file, write records to the file, or both read and write records. If you omit this argument, the default is to allow both reading and writing of records. For the share argument, you can code members that let other users readrecords, write records, or both read and write records at the same time that the first user is accessing the file.

Streams cont. You can code the None member to prevent sharing of the file. What you’re trying to avoid is two users writing to a file atthe same time, which could lead to errors. So if you code the access argumentas ReadWrite or Write, you can code the share argument as Read or None. On the other hand, if you code the access argument as Read, you may want to code the share argument as Read or ReadWrite. Then, other applications may be able to write new data to the file while you’re using it. However, when you set the share argument, additional permissions may be needed to share this file while it’s being used by the current process. In that case, you can use the Close method to close the file when you’re done with it to allow other processes to access the file.The first example shows how to Open a file stream for writing. Since this example uses the Write member to specify file access, this file stream can only be used to write to the file, not to read from it. And since this example uses the Create member for the mode argument, this code will create a new file if the file doesn’t exist, or it will overwrite the existing file if the file already does exist. However, if the directory for this file doesn’t exist, a DirectoryNotFoundException will be thrown as described in the next figure.The second example shows how to open a file stream for reading. This works similarly to opening a file stream for writing. However, the Open memberis used to specify the mode argument. As a result, if the file doesn’t exist, a FileNotFoundException will be thrown as described in the next figure.

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. (repeat) // 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. You use a BinaryWriter object to write data to a binary file. In most cases, you’llwrite one field at a time in a prescribed sequence. Unlike the BinaryReader class, which provides several methods for reading fieldsthat contain different types of data, the BinaryWriter class provides a single Write method for writing data to a file. This method determines the type of data beingwritten based on the data type of the argument. In a binary file, there’s no termination character to indicate where one recordends and another begins. Because of that, you can’t read an entire record at once. Instead, you have to read one character or one field at a time. To do that, you use the Read methods of the BinaryReader class. When you do, you must use the appropriate method for the data type of the field thatyou want to read. To read a Boolean field, for example, you use the ReadBoolean method. To read a Decimal field, you use the ReadDecimal method.The BinaryReader class provides methods to read most of the data typesprovided by the .NET Framework.

The basic syntax for creating a BinaryWriter object cont. For a complete list of methods, see the online help information for the BinaryReader class. https://docs.microsoft.com/en-us/dotnet/api/system.io.binaryreader?view=netframework-4.7.2 Before you read the next character or field, you want to be sure that you aren’t at the end of the file. To do that, you use the PeekChar method. Then, if there’s at least one more character to be read, this method returns that characterwithout advancing the cursor to the next position in the file. If there isn’t another character, the PeekChar method returns a value of -1. Then, you can use the Close method to close the binary reader and the associated file stream.

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 (Most common) 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)