Download presentation
Presentation is loading. Please wait.
1
How to work with files and data streams
Murach Chapter 21
2
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.
3
Main System.IO File Classes and Operations
4
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 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);
5
Very Common System.IO Methods
Exists(path) Delete(path) Copy(source, destination) Move(Source, destination)
6
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 2015\Files\"; private const string path = dir + "Products.dat";
7
Two types of Files and Streams
8
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.
9
System.IO classes used to work with files and streams
10
The syntax for creating a FileStream object
11
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.
12
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.
13
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.
14
System.IO classes used to work with files and streams
15
Code that creates a FileStream object for writing
string path 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 "; - will be in bin string path - 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.
16
The exception classes for file I/O
17
Code that uses exception classes
string dirPath 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();
18
The basic syntax for creating a StreamWriter object
19
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();
20
The basic syntax for creating a StreamReader object
21
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();
22
Again
23
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 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));
24
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;
25
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();
26
The basic syntax for creating a BinaryWriter object
27
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.
28
The basic syntax for creating a BinaryWriter object cont.
For a complete list of methods, see the online help information for the BinaryReader class. 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.
29
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();
30
The BASIC (Most common) syntax for creating a BinaryReader object
31
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();
32
A class that works with a binary file
public class ProductDB { private const string dir 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));
33
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;
34
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();
35
Project 5-1 Maintain student scores (text file)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.