CHPTR 4 ADT-II
CHPTR 4 ADT-II
Subject Instructor
Prof. J. T. Patil
Assistant Professor, Information Technology Department, JJMCOE, Jaysingpur
Structure overview
Class T.Y.Btech Semester- VI
Credits 03
C# fundamentals:
Data types - Value types, Reference types, boxing and unboxing, Arrays, Pass by value and
Unit 2 by reference and out parameters, params parameter. Namespaces, classes, objects, structs: 3 Hr
definition and creation.
File handling:
The abstract stream class, working with StreamWriters and StreamReaders, Working with
Unit 4 4 Hr
StringWriters and StringReaders, Working with BinaryWriters and BinaryReaders.
ADO.NET:
Unit 5 Exploring ADO.net Entity framework, Connected and disconnected architecture, data 4 Hr
access with ADO.net.
Reference Books:
1. Microsoft Visual C# 2010 Step by Step: John sharp, Microsoft Press
2. NET 4.5 Programming (6 – in -1) Black Book – Kogent – Dreamtech
Press
3. CLR via C# :Jeffrey Richter, Microsoft Press, 3rd edition
4. ASP.Net 4.5 Black Book ,Dreamtech ,Wiley International.
Unit 4 : File handling
Name: abc.txt
When you open File using C# for reading and writing purposes it
becomes Stream.
What is Stream?
Output Stream: This Stream is used to write data into a file, which is known as a
write operation.
A stream is a sequence of bytes that is used for communication. When you open
I/O => Streams: C#
C# programs perform I/O through streams.
1. Console.In,
2. Console.Out,
3. Console.Error,
These are available to all programs that use the System namespace.
Console.Out - refers to the standard output stream. By default,
this is the console. When you call Console.WriteLine( ), for
example, it automatically sends information to Console.Out
Console.In - refers to standard input, which is, by default, the
keyboard.
Console.Error - refers to the standard error stream, which is also
the console by default.
The Stream Classes
The .NET Framework defines both byte and character stream classes.
The core stream classes are defined within the System.IO namespace.
To use these classes, you will usually include the following statement
near the top of your program:
using System.IO;
The reason that you don’t have to specify System.IO for console input
and output is that the Console class is defined in the System namespace.
The Stream Class
The core stream class is System.IO.Stream.
The term File Handling in C# refers to the various operations that we can
perform on a file such as creating a file, reading data from the file, writing
data into the file, appending the file, etc.
Reading: This operation is the basic read operation where the data is going to be read from a file.
Writing: This operation is the basic write operation where the data is going to be written to a file.
By default, all existing contents are removed from the file, and new content is written in the file.
Appending: This operation is the same as the write operation where the data is going to be written
to a file. The only difference between Write and Append is that the existing data in the file will not
be overwritten. With Append, the new data is going to be added at the end of the file.
System.IO Namespace in C#
Note: The FileInfo, DirectoryInfo, and DriveInfo classes have instance methods.
The following table describes commonly used classes in the System.IO
namespace.
FileStream Class in C#?
With the help of FileStream Class, we can easily read and write data
into files.
How to use FileStream Class in
C#?
To use FileStream Class in C#, first of all, we need to include
the System.IO namespace and then we need to create an instance of
the FileStream class either to create a new file or to open an existing
file.
The simplest way to create an instance of FileStream Class
path: A relative or absolute path for the file that the current FileStream object will
encapsulate.
access: A constant that determines how the file can be accessed by the FileStream object.
This also determines the values returned by the System.IO.FileStream.CanRead and
System.IO.FileStream.CanWrite properties of the FileStream object.
1. public FileStream(string path, FileMode mode, FileAccess access,
FileShare share): This overloaded version Initializes a new instance of
the System.IO.FileStream class with the specified path, creation mode,
read/write permission, and sharing permission.
Path, mode & access: same as a previous
share: A constant that determines how the file will be shared by processes.
The path parameter is nothing but a string value that contains the path
where the file is going to be created or the path of an existing file whose
data we want to access.
The rest three parameters i.e. FileMode. FileAccess and FileShare are
FileStream
1. Create:
2. CreateNew:
3. Append:
4. Open:
5. OpenOrCreate:
6. Truncate:
FileAccess in C#:
It has the following three constant values.
1. Read– It gives read access to the file. Data can be read from the
file. Combine with Write for read/write access.
3. ReadWrite – It gives read and writes access to the file. Data can
be written to and read from the file.
FileShare in C#:
It has the following Six constant values.
1. None
2. Read
3. Write
4. ReadWrite
5. Delete
6. Inheritable
Program: Create text file .
using System.IO;
namespace Filestream_Demo
{
class Program
{
static void Main(string[] args)
{
String path = @"G:\myFile.txt"; //verbatim literal
FileStream file = new FileStream(path, FileMode.Create);
Console.WriteLine("File created...");
file.Close();
Console.ReadLine();
}
}
Program: write data into text file .
using System.IO;
namespace Filestream_Demo
{
class Program
{
static void Main(string[] args)
{
String path = @"G:\myFile.txt"; //verbatim literal
using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.Read))
{
file.WriteByte(65); //A
Console.WriteLine("File created...");
}
//file.Close();
Console.ReadLine();
}
Character-Based File I/O
In general, to perform character-based file operations, you will wrap
a FileStream inside either a StreamReader or a StreamWriter.
These classes automatically convert a byte stream into a character
stream, and vice versa
StreamWriter is derived from TextWriter.
StreamWriter(Stream stream)
Close(): This method closes the current StreamWriter object and the underlying
stream.
Flush(): This method Clears data from all buffers for the current writer and
causes any buffered data to be written to the underlying stream.
Write(): It Writes data to the stream. It has different overloads for different data
types to write in the stream.
WriteLine: It is the same as Write() but it adds the newline character at the end
of the data. It has different overloads for different data types to write in the
stream.
StreamReader.
here:
StreamReader(Stream stream)
However, there are many ways to read text files in C# but StreamReader Class is more popular
in the list.
While working with C# StreamReader Class, you need to remember the following points.
Implements a TextReader that reads characters from a byte stream in a particular encoding.
Peek(): This method returns the next available character but does not consume it. An integer
represents the next character to be read, or -1 if there are no characters to be read or if the
stream does not support seeking.
Read(): This method reads the next character from the input stream and advances the
character’s position by one character. The next character from the input stream is represented
as a System.Int32 object, or -1 if no more characters are available.
ReadLine(): This method Reads a line of characters from the current stream and returns the
data as a string. The next line from the input stream, or null if the end of the input stream is
reached.
Properties:
EndOfStream: It gets a value that indicates whether the current stream position
is at the end of the stream.
As its name says BinaryWriter writes binary files that use a specific data layout for its bytes.
The BinaryWriter in C# creates a binary file that is not human-understandable but the machine can
understand it.
In order to create an object of BinaryWriter, we need to pass an object of Stream to the constructor of
the BinaryWriter class.
The BinaryWriter class in C# provides methods that simplify writing primitive data types to a stream.
If you don’t provide types of encoding while creating objects then default encoding UTF-8 will be
Methods of BinaryWriter Class in C#:
Write(String): This method is used to write a length-prefixed string to this stream in the current
encoding of the BinaryWriter and advances the current position of the stream in accordance with the
encoding used and the specific characters being written to the stream.
Write(float): This method is used to write a four-byte floating-point value to the current stream and
advances the stream position by four bytes.
Write(long): This method is used to write an eight-byte signed integer to the current stream and advances
the stream position by eight bytes.
Write(Boolean): This method is used to write the one-byte Boolean value to the present stream; 0
represents false while 1 represents true.
Write(Byte): This method is used to write an unsigned byte to the present stream and then it advances
the position of the stream by one byte.
Write(Char): This method is used to write Unicode characters to the present stream and also it advances
the present stream position according to the character encoding used and according to the characters
being written to the present stream.
Write(Decimal): This method is used to write a decimal value to the present stream and also it advances
the position of the current stream by sixteen bytes.
Write(Double): This method is used to write an eight-byte floating-point value to the present stream and
then it also advances the position of the current stream by eight bytes.
Write(Int32): This method is used to write a four-byte signed integer to the present stream and then it
How to Create an Instance of BinaryWriter Class in C#?
The StringWriter Class in C# is derived from the TextWriter class and this StringWriter
class is mainly used to manipulate strings rather than files.
So, we can write a character either with Write(Char) or WriteAsync(Char) method and we
can write a string with Write(String) or WriterAsync(String) method.
Constructors of StringWriter in C#
Close(): This method is used to close the current StringWriter and the underlying stream.
Dispose(): This method is used to release the unmanaged resources used by the System.IO.StringWriter
and optionally releases the managed resources.
FlushAsync(): This method is used to asynchronously clear all buffers for the current writer and causes
any buffered data to be written to the underlying device.
GetStringBuilder(): This method is used to return the underlying StringBuilder.
ToString(): This method is used to return a string containing the characters written to the current
StringWriter so far.
Write(char value): This method is used to write a character to the string.
Write(string value): This method is used to write a string to the current string.
WriteAsync(char value): This method is used to write a character to the string asynchronously.
WriteAsync(string value): This method is used to write a string to the current string asynchronously.
WriteLine(String): This method is used to Write a string followed by a line terminator to the text string or
stream.
WriteLineAsync(string value): This method is used to write a string followed by a line terminator
asynchronously to the current string.
Example to Understand StringWriter Class in
C#:
using System; //Store Data on StringBuilder
using System.Text; stringWriter.WriteLine(text);
stringWriter.Flush();
using System.IO; stringWriter.Close();
namespace StringWriter_StringReader_Demo //Read Entry
StringReader reader = new
{ StringReader(stringBuilder.ToString());
class Program //Check to End of File
while (reader.Peek() > -1)
{ {
static void Main(string[] args) Console.WriteLine(reader.ReadLine());
}
{ Console.ReadKey();
string text = "Hello. This is First Line \nHello. This }}}
is Second Line \nHello. This is Third Line";
//Writing string into StringBuilder
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new
StringWriter(stringBuilder);
Thank You!