0% found this document useful (0 votes)
11 views30 pages

Chapter Five C#

The document discusses file manipulation in C# using streams. It defines streams as ordered sequences of bytes that connect applications or devices. Streams allow only sequential access to data. The document covers basic stream operations like creation, reading, writing, positioning and closing. It distinguishes between binary streams that work with raw data and text streams that work with character and string data. Binary streams use FileStream, BinaryReader and BinaryWriter classes while text streams use TextReader, TextWriter, StreamReader and StreamWriter classes. Examples are provided for reading from and writing to binary and text files using the appropriate stream classes.

Uploaded by

Gofere Tube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

Chapter Five C#

The document discusses file manipulation in C# using streams. It defines streams as ordered sequences of bytes that connect applications or devices. Streams allow only sequential access to data. The document covers basic stream operations like creation, reading, writing, positioning and closing. It distinguishes between binary streams that work with raw data and text streams that work with character and string data. Binary streams use FileStream, BinaryReader and BinaryWriter classes while text streams use TextReader, TextWriter, StreamReader and StreamWriter classes. Examples are provided for reading from and writing to binary and text files using the appropriate stream classes.

Uploaded by

Gofere Tube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Windows Programming

Chapter Five
File Manipulation in C#

1 Prepared by Tesfa K. 5/31/2022


Streams
 You can use streams when your program needs to "read" or "write"
data to an external data source such as files, servers etc.
 It is important to say that the term input is associated with reading
data, whereas the term output is associated with writing data.
 A stream is an ordered sequence of bytes, which is sent from
one application or input device to another application or
output device.
 These bytes are written and read one after the other and always arrive in
the same order as they were sent.
 Streams allow sequential data access.
 You can manipulate the data only in the order in which it arrives from the
stream.
 You cannot take the first, than the eight, third, thirteenth byte and so on.
 Streams do not allow random access to their data, only sequential.

2 Prepared by Tesfa K. 5/31/2022


Streams…
 Streams are the primary means of exchanging information in
the computer world.
 Because of streams, different applications are able to access files
on the computer and are able to establish network
communication between remote computers.
 Streams are data communication channel that connects two
devices or applications. Hence we can consider streams as pipes
that connect two points.
 For example computer and peripheral device are connected
with stream (camera, mouse, keyboard, USB stick, soundcard,
printer, scanner etc.).

3 Prepared by Tesfa K. 5/31/2022


Streams…
 To process a file, first you have to open a stream to the
corresponding file, then perform read/write operation,
and finally close the stream.
 Streams are opened before we can begin working with
them and are closed after they have served their purpose.
 Closing the stream is very important and must not be left
out, because you may lose data or damaging the file.

4 Prepared by Tesfa K. 5/31/2022


Basic Operations with Streams
Creation
 To create or open a stream means to connect the stream to a data
source.
 For example, when we have a file stream, then we pass the file name and
the file mode in which it is to be opened (reading, writing or reading and
writing simultaneously).
FileStream file = new FileStream("E:/Binary.dat", FileMode.Append);
Reading
 Reading means extracting data from the stream.
 Reading is always performed sequentially from the current position of the
stream.
 Reading is a blocking operation, and if the other party has not sent
data while we are trying to read or the sent data has not yet arrived,
there may occur a delay – a few milliseconds to hours, days or greater.

5 Prepared by Tesfa K. 5/31/2022


Basic Operations with Streams…
Writing
 Writing means sending data to the stream in a specific way.
 The writing is performed from the current position of the stream.
 Writing may be a potentially blocking operation, before the data is sent on its way.
Positioning
 Positioning or seeking in the stream means to move the current position of the
stream.
 Moving is done according to the current position such as beginning of the
stream or the end of the stream or we can skip a number of byte.
 Moving can be done only in streams that support positioning.
 Note that :- file streams typically maintain positioning while network streams do
not.

6 Prepared by Tesfa K. 5/31/2022


Basic Operations with Streams…
Closing
 To close or disconnect a stream means to complete
the work with the stream and releases the occupied
resources.
 Closing must take place as soon as possible after the
stream has served its purpose, because a resource
opened by a user, usually cannot be used by other
users (including other programs on the same
computer that run parallel to our program).

7 Prepared by Tesfa K. 5/31/2022


Types of stream
 In .NET Framework classes for working with streams
are located in the namespace System.IO.
 We can distinguish two main types of streams – those
who work with binary data [binary streams ] and those
who work with text data[text streams ].
 Sometimes, for convenience, a sequence of bytes can be
treated as text (in a predefined encoding) and is
referred to as a text stream.
 The main classes in the System.IO namespace are Stream
(abstract base class for all streams in .NET Framework),
BufferedStream, FileStream, MemoryStream,
GZipStream and NetworkStream.

8 Prepared by Tesfa K. 5/31/2022


Binary Streams
 Binary streams, as their name suggests, work with binary (raw) data.
 The main classes that we use to read and write from and to binary
streams are: FileStream, BinaryReader and BinaryWriter.
 The class FileStream provides us with various methods for reading
and writing from a binary file (read / write one byte and a sequence of
bytes), skipping a number of bytes, checking the number of bytes
available and, of course, a method for closing the stream.
 We can get an object of that class by calling his constructor with
parameter-a file name.

9 Prepared by Tesfa K. 5/31/2022


Binary Streams…
 The class BinaryWriter enables you to write primitive
types and binary values in a specific encoding to a stream.
 It has one main method – Write(…), which allows
recording of any primitive data types – integers,
characters, Booleans, arrays, strings and more.
 BinaryReader allows you to read primitive data types
and binary values recorded using a BinaryWriter.
 Its main methods allow us to read a character, an array of
characters, integers, floating point, etc.
 Like the previous two classes, we can get on object of that
class by calling its constructor.

10 Prepared by Tesfa K. 5/31/2022


Example Binary Streams…
1. class Program
2. {
3. static void Main(string[] args)
4. {
5. FileStream file = new FileStream("E:/Binary.dat", FileMode.Append);
6. BinaryWriter BWriter = new BinaryWriter(file);
7. BWriter.Write("computer");
8. BWriter.Write(true);
9. BWriter.Write('a');
10. BWriter.Close();
11. file.Close();
12. }
13. }

11 Prepared by Tesfa K. 5/31/2022


Example Binary Streams…
1. class Program
2. {
3. static void Main(string[] args)
4. {
5. FileStream file = new FileStream("E:/BinaryTempType.dat", FileMode.Open);
6. BinaryReader BReader = new BinaryReader(file);
7. String data = BReader.ReadString();
8. bool b = BReader.ReadBoolean();
9. char ch = BReader.ReadChar();
10. Console.WriteLine(data + " " + b + " " + ch);
11. BReader.Close();
12. file.Close();
13. Console.ReadKey();
14. }
15. }

12 Prepared by Tesfa K. 5/31/2022


Text Streams
 Text streams are very similar to binary, but only work with text data
or a sequence of characters (char) and strings (string).
 The main classes for working with text streams in .NET are
TextReader and TextWriter.
 They are abstract classes, and they cannot be instantiated.
 These classes define the basic functionality for reading and writing for
the classes that inherit them.
 Their more important methods are:
 ReadLine() – reads one line of text and returns a string.
 ReadToEnd() – reads the entire stream to its end and returns a
string.
 Write() – writes a string to the stream.
 WriteLine() – writes one line of text into the stream.

13 Prepared by Tesfa K. 5/31/2022


Text Streams…
 StreamReader and StreamWriter class directly inherit the
TextReader and TextWriter classes and implement
functionality for reading and writing textual information to and
from a file.
 To create an object of type StreamReader or
StreamWriter, we need a file or a string, containing the file
path.
 Working with these classes, we can use all of the methods that
we are already familiar with, to work with the console.
 Reading and writing to the console is much like reading and
writing respectively with StreamReader and StreamWriter.

14 Prepared by Tesfa K. 5/31/2022


StreamReader Class for Reading a Text File
 C# provides several ways to read files but not all are easy.
 This is why we will use the StreamReader class.
 The System.IO. StreamReader class provides the easiest
way to read a text file, as it resembles reading from
the console.
Opening a Text File for Reading
 You can simply create a StreamReader from a filename
(or full file path).
 On its creation, we can also specify the character
encoding.
 Here is an example of how an object of the class
StreamReader can be created:

15 Prepared by Tesfa K. 5/31/2022


StreamReader Class for Reading a Text File…
 Here is an example of how an object of the class StreamReader can be created:
// Create a StreamReader connected to a file
StreamReader reader = new StreamReader("D:/newfile.txt");
// Read the file here …
// Close the reader resource after you've finished using it
reader.Close();
 The first thing to do, when reading from a text file, is to create a variable of type
StreamReader, which we can associate with a specific file from the file system on
our computer.
 To do this we need only pass the file path as a parameter to the constructor.
 Note that if the file is located in the folder where the compiled project
(subdirectory bin\Debug) is, we can only provide its filename.
 Otherwise, we have to provide the full file path or relative path.
 When working with files we can use full paths (e.g. C:\Temp\example.txt) or relative
paths, to the directory from which the application was started (e.g. ..\..\example.txt).

16 Prepared by Tesfa K. 5/31/2022


Example
 In the following example we create an object of type StreamReader to read the
file and loop though it line by line:

1. using System.IO; 11. while (line != null)


2. class FileReader
3. { 12. {
4. static void Main() 13. lineNumber++;
5. {
6. StreamReader reader = new 14. Console.WriteLine("Line {0}: {1}",
StreamReader("D:/newfile.txt"); lineNumber, line);
7. int lineNumber = 0; 15. line = reader.ReadLine();
8. // Read first line from the text file 16. }
9. string line =reader.ReadLine();
17. // Close the resource after you've
10. // Read the other lines from the text finished using it
file
18. reader.Close();
19. }
20. }

17 Prepared by Tesfa K. 5/31/2022


Example Description
 The first part of our program is already well known –
create a variable of type StreamReader, to whose
constructor we pass the file’s name, which will be read.
 The parameter of the constructor is the path to the file.
 After that, we create a variable – counter, whose purpose
is to count and display on which row of the file we are
currently located.
 Then, we create a variable that will store each read line.
With its creation, we directly read the first line of text file.
 If the text file is empty, the method ReadLine() of the
StreamReader object will return null.

18 Prepared by Tesfa K. 5/31/2022


Example Description…
 For the main part – reading the file line by line, we will use a while loop.
 The condition for the loop is: as long as there is something in the variable line,
we should continue reading.
 In the body of the loop, our task is to increase the value of the counter
variable by one and then print the current line in the format we like.
 Finally, again we use ReadLine() to read the next line in the file and write it
in the variable line.
 For printing, we use a method that is well known to us from the tasks, which
required something to be printed on to the console – WriteLine().
 Once we have read everything we need from the file, we should not forget to
close the object StreamReader, as to avoid loss of resources.
 For this, we use the method Close().

19 Prepared by Tesfa K. 5/31/2022


Writing to a Text File
 Text files are very convenient for storing various types of
information.
 For example, we can record the results of a program.
 For writing to a text file, we will use methods defined in a
StreamWriter class.
The StreamWriter Class
 The class StreamWriter is part of the System.IO
namespace and is used exclusively for working with text data.
 It resembles the class StreamReader, but instead of methods
for reading, it offers similar methods for writing to a text file.
 Unlike other streams, before writing data to the desired
destination, StreamWriter turns it into bytes.

20 Prepared by Tesfa K. 5/31/2022


Writing to a Text File…
 We can create an instance of the class in the following
way:
StreamWriter writer = new StreamWriter("D:/newfile.txt");
 In the constructor of the class can pass as a parameter a
file path, as well as an existing stream, to which we will
write, or an encoding scheme.
 The StreamWriter class has several predefined
constructors, depending on whether we will write to a file
or a stream.

21 Prepared by Tesfa K. 5/31/2022


Example
1. class FileWriter 16. writer.Close();
2. { 17. }}
3. static void Main() 18. // Read the other lines from the
4. { text file
5. // Create a StreamWriter instance 19. while (line != null)
6. StreamWriter writer = new 20. {
StreamWriter("D:/newfile.txt"); 21. lineNumber++;
7. // Ensure the writer will be closed 22. Console.WriteLine("Line {0}: {1}",
8. using (writer) lineNumber, line);
9. { 23. line = reader.ReadLine();
10. // Loop through the numbers from 1 24. }
to 20 and 25. // Close the resource
11. for (int i = 1; i <= 20; i++) 26. reader.Close();
12. {
13. writer.WriteLine(i);
14. }
15. }

22 Prepared by Tesfa K. 5/31/2022


Input / Output Exception Handling
 Many of the operations performed on the files, can cause exceptional
situations. Hence it important to detect and handle those exceptions.
 the most common exception when working with files is the
FileNotFoundException
 It can occur when creating StreamReader.
 When setting a specified encoding by the creation of a StreamReader or a
StreamWriter object, an ArgumentException can be thrown.
 This means, that the encoding we have chosen is not supported.

StreamReader reader = new StreamReader("test.txt", Encoding.GetEncoding("UTF-8"));

 Another common mistake is IOException.


 This is the base class for all IO errors when working with streams.

23 Prepared by Tesfa K. 5/31/2022


Input / Output Exception Handling…
 The standard approach for handling exceptions when working
with files is :-
 Declare variables of class StreamReader or StreamWriter in
try-catch block and perform input/output operation on the
file in this block.
 Handle the potential exceptions properly in catch block.
 To close the stream, use the structure using or use finally
constrict.
 The C# construct using(…) ensures that after leaving its
body, the method Close() will automatically be called.
 This will happen even if an exception occurs when reading
the file.

24 Prepared by Tesfa K. 5/31/2022


Example
1. class HandlingExceptions
2. { 16. catch (FileNotFoundException)
3. static void Main() 17. {
4. { 18. Console.Error.WriteLine(
5. string fileName = @"somedir\somefile.txt"; 19. "Can not find file {0}.", fileName);
6. try 20. }
7. { 21. catch (DirectoryNotFoundException)
8. StreamReader reader = new 22. {
StreamReader(fileName); 23. Console.Error.WriteLine(
9. Console.WriteLine( "File {0} successfully 24. "Invalid directory in the file path.");
opened.", fileName);
25. }
10. Console.WriteLine("File contents:");
26. catch (IOException)
11. using (reader)
27. {
12. {
28. Console.Error.WriteLine(
13. Console.WriteLine(reader.ReadToEnd());
29. "Can not open the file {0}", fileName);
14. }
30. }
15. }
31. }
32. }
25 Prepared by Tesfa K. 5/31/2022
Example Description
 The example demonstrates reading a file and printing its
contents to the console.
 If we accidentally have confused the name of the file or have
deleted it, an exception of type FileNotFoundException will be
thrown.
 In the catch block we intercept this sort of exception and if
such occurs, we will process it properly and print a message to
the console, saying that this file cannot be found.
 The same will happen if there were no directory named "somedir".
 Finally, for better security, we have also added a catch block for
IOExceptions.
 There all other IO exceptions, that might occur when working
with files, will be intercepted.

26 Prepared by Tesfa K. 5/31/2022


Example -Occurrences of a
Substring in a File
 Here is how to implement a simple program that counts how many times a
substring occurs in a text file.
 In the example, let’s look for the substring "C#" in a text file as follows:
 sample.txt
This is our "Intro to Programming in C#" book.
In it you will learn the basics of C# programming.
You will find out how nice C# is.
 We can implement the counting as follows: will read the file line by line and
each time we meet the desired word inside the last read line, we will increase
the value of a variable (occurrences).
 We will process the possible exceptional situations to enable users to receive
adequate information in case of errors.

27 Prepared by Tesfa K. 5/31/2022


Example -Occurrences of a Substring in a File …

static void Main() Console.WriteLine(


{ "The word {0} occurs {1} times.", word, occurrences);
string fileName = @"..\..\sample.txt"; }
string word = "C#";
}
try
catch (FileNotFoundException)
{
{
StreamReader reader = new
StreamReader(fileName); Console.Error.WriteLine(
using (reader) "Can not find file {0}.", fileName);
{ }
int occurrences = 0; catch (IOException)
string line = reader.ReadLine();
{
while (line != null)
Console.Error.WriteLine(
{
"Cannot read the file {0}.", fileName);
int index = line.IndexOf(word);
while (index != -1) }
{ }
occurrences++;
index = line.IndexOf(word, (index + 1));
}
line = reader.ReadLine();
}

28 Prepared by Tesfa K. 5/31/2022


Description of Occurrences of a
Substring in a File …
 You can see that the example is not very different from the previous ones.
 We initialize the variables outside of the try-catch block.
 Again, we use a while-loop to read the lines of the text file one by one.
 Inside its body, there is another while-loop, which counts how many times the
searched word occurs in the given line, and then increases the number of
occurrences.
 This is done using the method IndexOf(…) of the class String (remember
what it does in case you have forgotten).
 We do not forget to ensure the closing of the StreamReader object using
the using structure.
 All that remains is to print the results on to the console.
 For our example, the result is the following:
 The word C# occurs 3 times.

29 Prepared by Tesfa K. 5/31/2022


End of Chapter Five

30 Prepared by Tesfa K. 5/31/2022

You might also like