0% found this document useful (0 votes)
15 views50 pages

CHPTR 4 ADT-II

The document outlines the curriculum for the Application Development Tool-II course at Dr. J. J. Magdum College of Engineering, focusing on .NET, C#, and file handling techniques. It covers various topics including object-oriented programming, GUI programming, ADO.NET, and file I/O operations using StreamReader and StreamWriter classes. The course includes a mix of lectures and practical sessions, with a total of 3 credits and an evaluation scheme based on term work and practicals.

Uploaded by

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

CHPTR 4 ADT-II

The document outlines the curriculum for the Application Development Tool-II course at Dr. J. J. Magdum College of Engineering, focusing on .NET, C#, and file handling techniques. It covers various topics including object-oriented programming, GUI programming, ADO.NET, and file I/O operations using StreamReader and StreamWriter classes. The course includes a mix of lectures and practical sessions, with a total of 3 credits and an evaluation scheme based on term work and practicals.

Uploaded by

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

Dr. J. J.

Magdum College of Engineering,Jaysingpur

Department of Information Technology

Class: T. Y. BTech Semester- VI

Subject: : Application Development Tool-II

Subject Instructor
Prof. J. T. Patil
Assistant Professor, Information Technology Department, JJMCOE, Jaysingpur
Structure overview
Class T.Y.Btech Semester- VI

Course Title Application Development Tool-II

1. Basic knowledge of Object Oriented


Prerequisite/s
Programming

Teaching Scheme: Lecture/Tutorial/Practical 2hr/week,-----,2hr/week

Credits 03

Evaluation Scheme: Theory/Term work/Practical ------/25 marks/50 marks


Course Title
Introduction to .net:
Unit 1 Evolution of .net, Benefits of .net, CLR, CTS, MSIL, JIT, BCL, metadata and assemblies in 4 Hr
detail, GAC and strong name assemblies, Security Manager.

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.

Delegates and Events:


Creating and using delegates, multicasting with delegates, event sources, event handlers
GUI Programming: Introduction to GUI Application and their components, Windows
Unit 3 forms – buttons, check boxes, radio buttons, panels, group boxes, list boxes, picture boxes, 8 Hr
Menus, ToolStrips, StatusStrips and progress bars, events, Creating and using MDI
application.

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.

Collection and Generic:


Unit 6 Collection classes in .net, Understanding Generics, generic collection classes in .net. 3 Hr
 Text Book:
1. C# 4.0 The Complete Reference: Herbert Schildt, McGraw Hill.

 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

 The abstract stream class,

 working with StreamWriters and StreamReaders,

 Working with StringWriters and StringReaders,

 Working with BinaryWriters and BinaryReaders.


Introduction: What is a File?

 A file is a collection of data stored on a disk with a specific name,


extension, and directory path.

 Name: abc.txt

 Directory path: c:\Program files\demo\abc.txt

 For example: word file .docx, notepad files .txt etc.

 When you open File using C# for reading and writing purposes it
becomes Stream.
What is Stream?

 When a file is opened for reading or writing, it becomes a stram.

 A stream is a sequence of bytes travelling from a source to a destination over a


communication path. There are two main streams: the Input Stream and the
Output Stream.
 Input Stream: This Stream is used to read data from a file, which is known as a
read operation.

 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.

 A stream is an abstraction that either produces or consumes information.

 A stream is linked to a physical device by the I/O system.


The Predefined Streams
 Three predefined 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.

 Stream represents a byte stream and is a base class for


all other stream classes.
 It is also abstract, which means that you cannot
instantiate a Stream object.
File Handling in C#

 File handling allows to store/ retrieve data on permanent storage

 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#

 In C#, The System.IO namespace contains the required classes


used to handle the input and output streams and provide
information about file and directory structure.
 The parent class of file processing is Stream. Stream is an
abstract class used as the parent of the classes that implement the
necessary operations.
 file handling class hierarchy 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#?

 The FileStream Class in C# provides a stream for file operations.

 It can be used to perform both Synchronous and Asynchronous

Read and Write operations.

 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

1. public FileStream(string path, FileMode mode): This Constructor Initializes a new


instance of the FileStream class with the specified path and creation mode.

 path: A relative or absolute path for the file that the current FileStream object will
encapsulate.

 mode: A constant that determines how to open or create the file.

2. public FileStream(string path, FileMode mode, FileAccess access): This overloaded


version initializes a new instance of the FileStream class with the specified path, creation
mode, and read/write permission.

 path & mode: same as a previous

 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

 FileMode: It has the following six constant values.

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.

2. Write – It gives Write access to the file. Data can be written to


the file. Combine with Read 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.

 StreamReader is derived from TextReader.

 Thus, StreamWriter and StreamReader have access to the


methods and properties defined by their base classes.
Using StreamWriter
 The StreamWriter Class in C# is more popular in File Handling
and it is very helpful in writing text data into a file.
 It is easy to use and provides a complete set of constructors and
methods to work on it.
 StreamWriter class in C# is used for writing characters to stream
in a particular format.
 To create a character-based output stream, wrap a Stream object
(such as a FileStream) inside a StreamWriter.
 StreamWriter defines several constructors. One of its most popular is shown
here:

StreamWriter(Stream stream)

 Here, stream is the name of an open stream.

 This constructor throws an ArgumentException if stream is not opened for


output and an ArgumentNullException if stream is null.

 Once created, a StreamWriter automatically handles the conversion of


characters to bytes. When you are done with the StreamWriter, you must
close it.
StreamWriter:Methods

 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.

 Dispose(): It releases the unmanaged resources used by the StreamWriter and


 Program: Write User Input to a File using StreamWriter Class in C#:.
using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
StreamWriter streamWriter = new StreamWriter("D://MyFile.txt");
Console.WriteLine("Enter the Text that you want to write on File");
string inputData = Console.ReadLine();
streamWriter.Write(inputData);
Console.WriteLine("Data Has Been Written to the File");
streamWriter.Flush();
streamWriter.Close();
Console.ReadKey();
 Save Variable Data to File in C#
using StreamWriter Class
using System;  Continue….
using System.IO; using (StreamWriter streamWriter = new
StreamWriter(filePath))
namespace FileHandlinDemo
{
{
streamWriter.Write($"Sum of {a} + {b} =
class Program
{result}");
{
//No need to call the Flush and Close Method
static void Main(string[] args)
}
{
Console.WriteLine("Variable Data is Saved
//Set the file Path where you want to Create the File into the File");
string filePath = @"D:\MyFile.txt"; Console.ReadKey();
//Do Some Basic Operations using variables }}}
int a, b, result;
a = 15;
b = 20;
result = a + b;
Using a StreamReader

 To create a character-based input stream, wrap a byte stream inside a

StreamReader.

 StreamReader defines several constructors. A frequently used one is shown

here:

StreamReader(Stream stream)

 Here, stream is the name of an open stream.


StreamReader Class in C#
 The StreamReader class in C# allows us to read text files.

 Its implementation is easy and it is widely popular among developers.

 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.

 StreamReader class uses UTF-8 Encoding by default.

 StreamReader class is designed for character input in a particular encoding.

 Use this class for reading a standard text file.

 By default, it is not thread-safe.


Methods:
 Close(): The Close method Closes the StreamReader object and the underlying stream, and
releases any system resources associated with the reader.

 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:

 CurrentEncoding: It gets the current character encoding that the current


System.IO.StreamReader object is using.

 EndOfStream: It gets a value that indicates whether the current stream position
is at the end of the stream.

 BaseStream: It returns the underlying stream.


//It reads a line of characters from the current stream and
 Example to Read Data from a File using
StreamReader Class in C# returns the data as a string.
using System.IO; //It return the next line from the input stream, or null if the
namespace FileHandlinDemo end of the input stream is reached.
{ string strData = streamReader.ReadLine();
class Program // To Read the whole file line by line use While Loop as long
{ the strData is not null
static void Main(string[] args) while (strData != null)
{
{
//Create a Variable to Hold the String Path
//Print the String data
string filePath = "D://MyFile.txt";
Console.WriteLine(strData);
//Creating an Instance StreamReader Object to Read the Data
from the File Path //Then Read the next String data

StreamReader streamReader = new StreamReader(filePath); strData = streamReader.ReadLine();


Console.WriteLine("Content of the File"); }
// This is used to specify from where to start reading the input Console.ReadLine();
stream
//Close the streamReader Object
// BaseStream: Returns the underlying stream.
streamReader.Close();
// Seek: The new position within the current stream.
Console.ReadKey(); }}}
// SeekOrigin.Begi: Specifies the beginning of a stream
BinaryWriter Class in C#?
 The BinaryWriter class in C# is used to write Primitive type data types such as int, uint, or char
in the form of binary data to a stream.

 It is present under the System.IO namespace.

 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.

 It supports writing strings in a specific encoding.

 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#?

 public BinaryWriter(Stream output): It initializes a new instance of the BinaryWriter class


based on the specified stream and uses UTF-8 encoding. Here, the parameter output specifies
the output stream.
 public BinaryWriter(Stream output, Encoding encoding): It initializes a new instance of
the BinaryWriter class based on the specified stream and character encoding. Here, the
parameter output specifies the output stream and the parameter encoding specifies the character
encoding to use.
 public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen): It initializes a
new instance of the BinaryWriter class based on the specified stream and character encoding,
and optionally leaves the stream open. Here, the parameter output specifies the output stream
and the parameter encoding specifies the character encoding to use and the parameter
leaveOpen specifies true to leave the stream open after the BinaryWriter object is disposed
otherwise, false.
 protected BinaryWriter(): It initializes a new instance of the System.IO.BinaryWriter class
that writes to a stream.
 Syntax:
 using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(fileName,
FileMode.Create )))
{
//user code
 Example to Understand BinaryWriter Class in C#
using System;
using System.IO;
Output:
namespace FileHandlingDemo
{
class Program
{
static void Main(string[] args)
{
using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\MyBinaryFile.bin", FileMode.Create)))
{
//Writting Error Log
writer.Write("0x80234400");
writer.Write("Windows Explorer Has Stopped Working");
writer.Write(true);
}
Console.WriteLine("Binary File Created!");
Console.ReadKey(); }}}
BinaryReader class in C#?
 The BinaryReader class belongs to the System.IO namespace.
 BinaryReader is used to read primitive data types as binary values in a
particular encoding stream.
 BinaryReader works with Stream object i.e. in order to create an object
of BinaryReader, we need to pass the Stream object to its constructor.
 BinaryReader class has three overloaded constructors to work with
binary data.
 By default, BinaryReader uses UTF-8 encoding to read data until we
specify other character encodings while creating its object.
 The BinaryReader class in C# handles Binary (.bin) files.
 It reads primitive data types as binary values in a specific encoding.
 The BinaryReader class provides methods that simplify reading primitive
data types from streams.
How to Create an Instance of BinaryReader Class in C#?

 public BinaryReader(Stream input): It initializes a new instance of the


System.IO.BinaryReader class based on the specified stream and using UTF-8 encoding.
Here, the parameter input specifies the input stream.

 public BinaryReader(Stream input, Encoding encoding): It initializes a new instance of


the System.IO.BinaryReader class based on the specified stream and character encoding.
Here, the parameter input specifies the input stream and the parameter encoding specifies the
character encoding to use.

 public BinaryReader(Stream input, Encoding encoding, bool leaveOpen): It initializes a


new instance of the System.IO.BinaryReader class based on the specified stream and
character encoding, and optionally leaves the stream open. Here, the parameter input
specifies the input stream and the parameter encoding specifies the character encoding to use
and the parameter leaveOpen specifies true to leave the stream open after the BinaryReader
 Example to Understand BinaryReader
Class in C#:
//Writting Error Log
using System;
writer.Write("0x80234400");
using System.IO;
writer.Write("Windows Explorer Has Stopped Working");
namespace FileHandlingDemo
writer.Write(true);
{
}}
class Program
static void ReadDataFromBinaryFile()
{
{
static void Main(string[] args)
using (BinaryReader reader = new
{
BinaryReader(File.Open("D:\\MyBinaryFile2.bin",
WriteDataToBinaryFile();
FileMode.Open)))
ReadDataFromBinaryFile();
{
Console.ReadKey();
Console.WriteLine("Error Code : " + reader.ReadString());
}
Console.WriteLine("Message : " + reader.ReadString());
static void WriteDataToBinaryFile()
Console.WriteLine("Restart Explorer : " +
{
reader.ReadBoolean()); }}}}
using (BinaryWriter writer = new
BinaryWriter(File.Open("D:\\MyBinaryFile2.bin",
FileMode.Create)))
{
StringWriter 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.

 The StringWriter class enables us to write a string either synchronously or asynchronously.

 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#

 public StringWriter(): It initializes a new instance of the System.IO.StringWriter class.


 public StringWriter(IFormatProvider formatProvider): It initializes a new instance of the
StringWriter class with the specified format control. The parameter formatProvider specifies a
System.IFormatProvider object that controls formatting
 public StringWriter(StringBuilder sb): It initializes a new instance of the StringWriter class that
writes to the specified System.Text.StringBuilder. The parameter sb specifies the StringBuilder
object to write to.
 public StringWriter(StringBuilder sb, IFormatProvider formatProvider): It initializes a new
instance of the StringWriter class that writes to the specified StringBuilder and has the specified
format provider. The parameter sb specifies the StringBuilder object to write to and the parameter
format Provider specifies a System.IFormatProvider object that controls formatting.
Methods of StringWriter Class 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!

You might also like