SlideShare a Scribd company logo
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 1
Chapter 21
How to work with
files and data streams
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 2
Objectives
Applied
1. Develop an application that requires the use of text or binary files.
Knowledge
1. Distinguish between a text file and a binary file.
2. Describe the use of FileStream, StreamReader, StreamWriter,
BinaryReader, and BinaryWriter objects.
3. Describe two common types of I/O exceptions.
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 3
System.IO classes used to work with drives and
directories
• Directory
• File
• Path
A statement that simplifies references to the
System.IO classes
using System.IO;
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 4
Common methods of the Directory class
• Exists(path)
• CreateDirectory(path)
• Delete(path)
• Delete(path, recursive)
Code that uses some of the Directory methods
string dir = @"C:C# 2010Files";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 5
Common methods of the File class
• Exists(path)
• Delete(path)
• Copy(source, dest)
• Move(source, dest)
Code that uses some of the File methods
string path = dir + "Products.txt";
if (File.Exists(path))
File.Delete(path);
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 6
A text file displayed in a text editor
A binary file displayed in a text editor
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 7
Two types of files
Type Description
Text A file that contains text (string) characters. The fields in
each record are typically delimited by special characters
like tab or pipe characters, and the records are typically
delimited by new line characters.
Binary A file that can contain a variety of data types.
Two types of streams
Stream Description
Text Used to transfer text data.
Binary Used to transfer binary data.
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 8
System.IO classes used to work with files and
streams
• FileStream
• StreamReader
• StreamWriter
• BinaryReader
• BinaryWriter
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 9
The syntax for creating a FileStream object
new FileStream(path, mode[, access[, share]])
Members in the FileMode enumeration
• Append
• Create
• CreateNew
• Open
• OpenOrCreate
• Truncate
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 10
Members in the FileAccess enumeration
• Read
• ReadWrite
• Write
Members in the FileShare enumeration
• None
• Read
• ReadWrite
• Write
Common method of the FileStream class
• Close()
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 11
Code that creates a FileStream object for writing
string path = @"C:C# 2010FilesProducts.txt";
FileStream fs = new FileStream(
path, FileMode.Create, FileAccess.Write);
Code that creates a new FileStream object for
reading
string path = @"C:C# 2010FilesProducts.txt";
FileStream fs = new FileStream(
path, FileMode.Open, FileAccess.Read);
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 12
The exception classes for file I/O
• IOException
• DirectoryNotFoundException
• FileNotFoundException
• EndOfStreamException
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 13
Code that uses exception classes
string dirPath = @"C:C# 2010Files";
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");
}
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 14
Code that uses exception classes (cont.)
catch(IOException ex)
{
MessageBox.Show(ex.Message, "IOException");
}
finally
{
if (fs != null)
fs.Close();
}
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 15
The basic syntax for creating a StreamWriter object
new StreamWriter(stream)
Common methods of the StreamWriter class
Method Description
Write(data) Writes the data to the output stream.
WriteLine(data) Writes the data to the output stream and
appends a line terminator (usually a carriage
return and a line feed).
Close() Closes the StreamWriter object and the
associated FileStream object.
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 16
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 + "|");
textOut.WriteLine(product.Price);
}
textOut.Close();
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 17
The basic syntax for creating a StreamReader
object
new StreamReader(stream)
Common methods of the StreamReader class
Method Description
Peek() Returns the next available character in the input
stream without advancing to the next position. If no
more characters are available, returns -1.
Read() Reads the next character from the input stream.
ReadLine() Reads the next line of characters from the input
stream; returns it as a string.
ReadToEnd() Reads the data from the current position to the end
of the input stream; returns it as a string.
Close() Closes both the StreamReader object and the
associated FileStream object.
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 18
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();
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 19
A class that works with a text file
using System;
using System.IO;
using System.Collections.Generic;
namespace ProductMaintenance
{
public class ProductDB
{
private const string dir = @"C:C# 2010Files";
private const string path = dir + "Products.txt";
public static List<Product> GetProducts()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Read));
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 20
A class that works with a text file (cont.)
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();
return products;
}
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 21
A class that works with a text file (cont.)
public static void SaveProducts(List<Product>
products)
{
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Create,
FileAccess.Write));
foreach (Product product in products)
{
textOut.Write(product.Code + "|");
textOut.Write(product.Description + "|");
textOut.WriteLine(product.Price);
}
textOut.Close();
}
}
}
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 22
The basic syntax for creating a BinaryWriter
object
new BinaryWriter(stream)
Common methods of the BinaryWriter class
• Write(data)
• Close()
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 23
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();
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 24
The basic syntax for creating a BinaryReader
object
new BinaryReader(stream)
Common methods of the BinaryReader class
• PeekChar()
• Read()
• ReadBoolean()
• ReadByte()
• ReadChar()
• ReadDecimal()
• ReadInt32()
• ReadString()
• Close()
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 25
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();
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 26
A class that works with a binary file
using System;
using System.IO;
using System.Collections.Generic;
namespace ProductMaintenance
{
public class ProductDB
{
private const string dir = @"C:C# 2010Files";
private const string path = dir + "Products.dat";
public static List<Product> GetProducts()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
BinaryReader binaryIn =
new BinaryReader(
new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Read));
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 27
A class that works with a binary file (cont.)
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();
return products;
}
Murach’s C#
2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 28
A class that works with a binary file (cont.)
public static void SaveProducts(List<Product>
products)
{
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();
}
}
}

More Related Content

What's hot

C# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slidesC# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-13-slides
C# Tutorial MSM_Murach chapter-13-slidesC# Tutorial MSM_Murach chapter-13-slides
C# Tutorial MSM_Murach chapter-13-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesC# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-07-slides
C# Tutorial MSM_Murach chapter-07-slidesC# Tutorial MSM_Murach chapter-07-slides
C# Tutorial MSM_Murach chapter-07-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesC# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-11-slides
C# Tutorial MSM_Murach chapter-11-slidesC# Tutorial MSM_Murach chapter-11-slides
C# Tutorial MSM_Murach chapter-11-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesC# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slides
Sami Mut
 
C# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesC# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slides
Sami Mut
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
Mahmoud Ouf
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
Mahmoud Ouf
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
JOSEPHINEA6
 
FP304 DATABASE SYSTEM FINAL PAPER
FP304    DATABASE SYSTEM FINAL PAPERFP304    DATABASE SYSTEM FINAL PAPER
FP304 DATABASE SYSTEM FINAL PAPER
Syahriha Ruslan
 

What's hot (20)

C# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slidesC# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slides
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slides
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slides
 
C# Tutorial MSM_Murach chapter-13-slides
C# Tutorial MSM_Murach chapter-13-slidesC# Tutorial MSM_Murach chapter-13-slides
C# Tutorial MSM_Murach chapter-13-slides
 
C# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesC# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slides
 
C# Tutorial MSM_Murach chapter-07-slides
C# Tutorial MSM_Murach chapter-07-slidesC# Tutorial MSM_Murach chapter-07-slides
C# Tutorial MSM_Murach chapter-07-slides
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slides
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesC# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slides
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slides
 
C# Tutorial MSM_Murach chapter-11-slides
C# Tutorial MSM_Murach chapter-11-slidesC# Tutorial MSM_Murach chapter-11-slides
C# Tutorial MSM_Murach chapter-11-slides
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slides
 
C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesC# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slides
 
C# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesC# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slides
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
FP304 DATABASE SYSTEM FINAL PAPER
FP304    DATABASE SYSTEM FINAL PAPERFP304    DATABASE SYSTEM FINAL PAPER
FP304 DATABASE SYSTEM FINAL PAPER
 

Similar to C# Tutorial MSM_Murach chapter-21-slides

Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
Techglyphs
 
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
Ángel Jesús Martínez Bernal
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on python
kannikadg
 
Database driven web pages
Database driven web pagesDatabase driven web pages
Database driven web pages
Information Technology
 
Web app development_html_01
Web app development_html_01Web app development_html_01
Web app development_html_01
Hassen Poreya
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
Gaurav Singh
 
VRE Cancer Imaging BL RIC Workshop 22032011
VRE Cancer Imaging BL RIC Workshop 22032011VRE Cancer Imaging BL RIC Workshop 22032011
VRE Cancer Imaging BL RIC Workshop 22032011
djmichael156
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
jorgeulises3
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Bill Buchan
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
Kamlesh Makvana
 
Amost 2011 keynote
Amost 2011 keynoteAmost 2011 keynote
Amost 2011 keynote
Wolfgang Grieskamp
 
Cis 534 Teaching Effectively--tutorialrank.com
Cis 534  Teaching Effectively--tutorialrank.comCis 534  Teaching Effectively--tutorialrank.com
Cis 534 Teaching Effectively--tutorialrank.com
Soaps82
 
Project: Designing a Secure Network
Project: Designing a Secure NetworkProject: Designing a Secure Network
Project: Designing a Secure Network
victor okoth
 
C# intro
C# introC# intro
16 implementation techniques
16 implementation techniques16 implementation techniques
16 implementation techniques
Majong DevJfu
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
laxmi.katkar
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet Introduction
Wei Sun
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
sangeetaSS
 
econstruct summary
econstruct summaryeconstruct summary
econstruct summary
Reinout van Rees
 
COM
COMCOM

Similar to C# Tutorial MSM_Murach chapter-21-slides (20)

Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
 
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
Automated Multiplatform Compilation and Validation of a Collaborative Reposit...
 
FDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on pythonFDP-faculty deveopmemt program on python
FDP-faculty deveopmemt program on python
 
Database driven web pages
Database driven web pagesDatabase driven web pages
Database driven web pages
 
Web app development_html_01
Web app development_html_01Web app development_html_01
Web app development_html_01
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
VRE Cancer Imaging BL RIC Workshop 22032011
VRE Cancer Imaging BL RIC Workshop 22032011VRE Cancer Imaging BL RIC Workshop 22032011
VRE Cancer Imaging BL RIC Workshop 22032011
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
Amost 2011 keynote
Amost 2011 keynoteAmost 2011 keynote
Amost 2011 keynote
 
Cis 534 Teaching Effectively--tutorialrank.com
Cis 534  Teaching Effectively--tutorialrank.comCis 534  Teaching Effectively--tutorialrank.com
Cis 534 Teaching Effectively--tutorialrank.com
 
Project: Designing a Secure Network
Project: Designing a Secure NetworkProject: Designing a Secure Network
Project: Designing a Secure Network
 
C# intro
C# introC# intro
C# intro
 
16 implementation techniques
16 implementation techniques16 implementation techniques
16 implementation techniques
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet Introduction
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
 
econstruct summary
econstruct summaryeconstruct summary
econstruct summary
 
COM
COMCOM
COM
 

More from Sami Mut

MSM_Time
MSM_TimeMSM_Time
MSM_Time
Sami Mut
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodia
Sami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
Sami Mut
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodia
Sami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
Sami Mut
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodia
Sami Mut
 

More from Sami Mut (6)

MSM_Time
MSM_TimeMSM_Time
MSM_Time
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodia
 

Recently uploaded

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 

Recently uploaded (20)

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 

C# Tutorial MSM_Murach chapter-21-slides

  • 1. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 1 Chapter 21 How to work with files and data streams
  • 2. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 2 Objectives Applied 1. Develop an application that requires the use of text or binary files. Knowledge 1. Distinguish between a text file and a binary file. 2. Describe the use of FileStream, StreamReader, StreamWriter, BinaryReader, and BinaryWriter objects. 3. Describe two common types of I/O exceptions.
  • 3. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 3 System.IO classes used to work with drives and directories • Directory • File • Path A statement that simplifies references to the System.IO classes using System.IO;
  • 4. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 4 Common methods of the Directory class • Exists(path) • CreateDirectory(path) • Delete(path) • Delete(path, recursive) Code that uses some of the Directory methods string dir = @"C:C# 2010Files"; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
  • 5. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 5 Common methods of the File class • Exists(path) • Delete(path) • Copy(source, dest) • Move(source, dest) Code that uses some of the File methods string path = dir + "Products.txt"; if (File.Exists(path)) File.Delete(path);
  • 6. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 6 A text file displayed in a text editor A binary file displayed in a text editor
  • 7. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 7 Two types of files Type Description Text A file that contains text (string) characters. The fields in each record are typically delimited by special characters like tab or pipe characters, and the records are typically delimited by new line characters. Binary A file that can contain a variety of data types. Two types of streams Stream Description Text Used to transfer text data. Binary Used to transfer binary data.
  • 8. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 8 System.IO classes used to work with files and streams • FileStream • StreamReader • StreamWriter • BinaryReader • BinaryWriter
  • 9. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 9 The syntax for creating a FileStream object new FileStream(path, mode[, access[, share]]) Members in the FileMode enumeration • Append • Create • CreateNew • Open • OpenOrCreate • Truncate
  • 10. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 10 Members in the FileAccess enumeration • Read • ReadWrite • Write Members in the FileShare enumeration • None • Read • ReadWrite • Write Common method of the FileStream class • Close()
  • 11. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 11 Code that creates a FileStream object for writing string path = @"C:C# 2010FilesProducts.txt"; FileStream fs = new FileStream( path, FileMode.Create, FileAccess.Write); Code that creates a new FileStream object for reading string path = @"C:C# 2010FilesProducts.txt"; FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read);
  • 12. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 12 The exception classes for file I/O • IOException • DirectoryNotFoundException • FileNotFoundException • EndOfStreamException
  • 13. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 13 Code that uses exception classes string dirPath = @"C:C# 2010Files"; 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"); }
  • 14. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 14 Code that uses exception classes (cont.) catch(IOException ex) { MessageBox.Show(ex.Message, "IOException"); } finally { if (fs != null) fs.Close(); }
  • 15. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 15 The basic syntax for creating a StreamWriter object new StreamWriter(stream) Common methods of the StreamWriter class Method Description Write(data) Writes the data to the output stream. WriteLine(data) Writes the data to the output stream and appends a line terminator (usually a carriage return and a line feed). Close() Closes the StreamWriter object and the associated FileStream object.
  • 16. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 16 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 + "|"); textOut.WriteLine(product.Price); } textOut.Close();
  • 17. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 17 The basic syntax for creating a StreamReader object new StreamReader(stream) Common methods of the StreamReader class Method Description Peek() Returns the next available character in the input stream without advancing to the next position. If no more characters are available, returns -1. Read() Reads the next character from the input stream. ReadLine() Reads the next line of characters from the input stream; returns it as a string. ReadToEnd() Reads the data from the current position to the end of the input stream; returns it as a string. Close() Closes both the StreamReader object and the associated FileStream object.
  • 18. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 18 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();
  • 19. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 19 A class that works with a text file using System; using System.IO; using System.Collections.Generic; namespace ProductMaintenance { public class ProductDB { private const string dir = @"C:C# 2010Files"; private const string path = dir + "Products.txt"; public static List<Product> GetProducts() { if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); StreamReader textIn = new StreamReader( new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
  • 20. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 20 A class that works with a text file (cont.) 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(); return products; }
  • 21. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 21 A class that works with a text file (cont.) public static void SaveProducts(List<Product> products) { StreamWriter textOut = new StreamWriter( new FileStream(path, FileMode.Create, FileAccess.Write)); foreach (Product product in products) { textOut.Write(product.Code + "|"); textOut.Write(product.Description + "|"); textOut.WriteLine(product.Price); } textOut.Close(); } } }
  • 22. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 22 The basic syntax for creating a BinaryWriter object new BinaryWriter(stream) Common methods of the BinaryWriter class • Write(data) • Close()
  • 23. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 23 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();
  • 24. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 24 The basic syntax for creating a BinaryReader object new BinaryReader(stream) Common methods of the BinaryReader class • PeekChar() • Read() • ReadBoolean() • ReadByte() • ReadChar() • ReadDecimal() • ReadInt32() • ReadString() • Close()
  • 25. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 25 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();
  • 26. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 26 A class that works with a binary file using System; using System.IO; using System.Collections.Generic; namespace ProductMaintenance { public class ProductDB { private const string dir = @"C:C# 2010Files"; private const string path = dir + "Products.dat"; public static List<Product> GetProducts() { if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); BinaryReader binaryIn = new BinaryReader( new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
  • 27. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 27 A class that works with a binary file (cont.) 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(); return products; }
  • 28. Murach’s C# 2010, C21 © 2010, Mike Murach & Associates, Inc.Slide 28 A class that works with a binary file (cont.) public static void SaveProducts(List<Product> products) { 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(); } } }