Learning Objectives
After completing this session, you will be able to: Read and write in a Text File
Read from a Stream File
Describe opening and appending in Log File Work with StreamReader and StreamWriter
Stream Class
The abstract base class Stream supports reading and writing bytes. Stream integrates
asynchronous support. Its default implementations define synchronous reads and writes in terms of their corresponding asynchronous methods, and vice versa. All classes that represent streams inherit from the Stream class.
Public Properties:
S.No Name Description
1 CanRead When overridden in a derived class, gets a value indicating whether the current stream supports reading.
2 CanSeek When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
3 CanTimeout Gets a value that determines whether the current stream can time out. 4 CanWrite When overridden in a derived class, gets a value indicating whether the
current stream supports writing.
5 Length When overridden in a derived class, gets the length in bytes of the stream.
6 Position When overridden in a derived class, gets or sets the position within the current stream.
7 ReadTimeout Gets or sets a value that determines how long the stream will attempt to read before timing out.
8 WriteTimeout Gets or sets a value that determines how long the stream will attempt to write before timing out.
Public Methods:
S.No Name Description
1 BeginRead Begins an asynchronous read operation. 2 BeginWrite Begins an asynchronous write operation. 3 Close Closes the current stream and releases any
resources (such as sockets and file handles) associated with the current stream.
4 CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
5 Dispose Overloaded. Releases all resources used by the Stream object.
6 EndRead Waits for the pending asynchronous read to complete. 7 EndWrite Ends an asynchronous write operation.
8 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)
9 Flush When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
10 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
11 GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
12 GetType Gets the Type of the current instance. (Inherited from Object.)
13 InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from
MarshalByRefObject.)
14 Read When overridden in a derived class reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
15 ReadByte Reads a byte from the stream and advances the position within the stream by one byte or returns 1 if at the end of the stream.
16 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.) 17 Seek When overridden in a derived class, sets the position
S.No Name Description
18 SetLength When overridden in a derived class, sets the length of the current stream.
19 Synchronized Creates a thread-safe (synchronized) wrapper around the specified Stream object.
20 ToString Returns a String that represents the current Object. (Inherited from Object.)
21 Write When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
22 WriteByte Writes a byte to the current position in the stream and advances the position within the stream by one byte.
Binary Reader
Reads primitive data types as binary values in a specific encoding.
Public properties:
S.No Name Description
1 BaseStream Exposes access to the underlying stream of the BinaryReader.
Public Methods:
S.No Name Description
1 Close Closes the current reader and the underlying stream.
2 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)
3 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
4 GetType Gets the Type of the current instance. (Inherited from Object.) 5 PeekChar Returns the next available character and does not advance the byte
or character position.
6 Read Overloaded. Reads characters from the underlying stream and advances the current position of the stream.
7 ReadBoolean Reads a Boolean value from the current stream and advances the current position of the stream by one byte.
8 ReadByte Reads the next byte from the current stream and advances the current position of the stream by one byte.
9 ReadBytes Reads count bytes from the current stream into a byte array and advances the current position by count bytes.
S.No Name Description
10 ReadChar Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.
11 ReadChars Reads count characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.
12 ReadDecimal Reads a decimal value from the current stream and advances the current position of the stream by sixteen bytes.
13 ReadDouble Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes. 14 ReadInt16 Reads a 2-byte signed integer from the current stream and advances the current position of the stream by two bytes. 15 ReadInt32 Reads a 4-byte signed integer from the current stream and
advances the current position of the stream by four bytes. 16 ReadInt64 Reads an 8-byte signed integer from the current stream and
advances the current position of the stream by eight bytes. 17 ReadSByte Reads a signed byte from this stream and advances the current
position of the stream by one byte.
18 ReadSingle Reads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes.
19 ReadString Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
20 ReadUInt16 Reads a 2-byte unsigned integer from the current stream using little endian encoding and advances the position of the stream by two bytes.
21 ReadUInt32 Reads a 4-byte unsigned integer from the current stream and advances the position of the stream by four bytes.
22 ReadUInt64 Reads an 8-byte unsigned integer from the current stream and advances the position of the stream by eight bytes.
23 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)
24 ToString Returns a String that represents the current Object. (Inherited from Object.)
Binary Writer
Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
Public Fields:
S.No Name Description
Public Properties:
S.No Name Description
1 BaseStream Gets the underlying stream of the BinaryWriter.
Public Methods:
S.No Name Description
1 Close Closes the current BinaryWriter and the underlying stream. 2 Equals Overloaded. Determines whether two Object instances are equal.
(Inherited from Object.)
3 Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
4 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
5 GetType Gets the Type of the current instance. (Inherited from Object.) 6 ReferenceEquals Determines whether the specified Object instances are the same
instance. (Inherited from Object.)
7 Seek Sets the position within the current stream.
8 ToString Returns a String that represents the current Object. (Inherited from Object.)
9 Write Overloaded. Writes a value to the current stream.
Text Reader
Represents a reader that can read a sequential series of characters.
Public fields:
S.No Name Description
1 Null Provides a TextReader with no data to read from.
Public Methods:
S.No Name Description
1 Close Closes the TextReader and releases any system resources associated with the TextReader. 2 CreateObjRef Creates an object that contains all the relevant
information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
3 Dispose Overloaded. Releases all resources used by the TextReader object.
4 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)
S.No Name Description
5 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
6 GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
7 GetType Gets the Type of the current instance. (Inherited from Object.)
8 InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
9 Peek Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the input stream.
10 Read Overloaded. Reads data from an input stream. 11 ReadBlock Reads a maximum of count characters from the
current stream and writes the data to buffer, beginning at index.
12 ReadLine Reads a line of characters from the current stream and returns the data as a string.
13 ReadToEnd Reads all characters from the current position to the end of the TextReader and returns them as one string.
14 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.) 15 Synchronized Creates a thread-safe wrapper around the specified
TextReader.
16 ToString Returns a String that represents the current Object. (Inherited from Object.)
This program demonstrates about Text Reader Class: using System;
using System.IO;
class TextRW {
static void Main() {
TextWriter stringWriter = new StringWriter(); using(TextWriter streamWriter =
{ WriteText(stringWriter); WriteText(streamWriter); } TextReader stringReader = new StringReader(stringWriter.ToString()); using(TextReader streamReader = new StreamReader("InvalidPathChars.txt")) { ReadText(stringReader); ReadText(streamReader); } }
static void WriteText(TextWriter textWriter) {
textWriter.Write("Invalid file path characters are: "); textWriter.Write(Path.InvalidPathChars);
textWriter.Write('.'); }
static void ReadText(TextReader textReader) { Console.WriteLine("From {0} - {1}", textReader.GetType().Name, textReader.ReadToEnd()); } } Text Writer
Represents a writer that can write a sequential series of characters. This class is abstract.
Public fields:
S.No Name Description
1 Null Provides a TextWriter with no backing store that can be written to, but not read from.
Public Properties:
S.No Name Description
1 Encoding When overridden in a derived class, returns the Encoding in which the output is written.
2 FormatProvider Gets an object that controls formatting.
3 NewLine Gets or sets the line terminator string used by the current TextWriter.
Public Methods:
S.No Name Description
1 Close Closes the current writer and releases any system resources associated with the writer.
2 CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
3 Dispose Overloaded. Releases all resources used by the TextWriter object.
4 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.) 5 Flush Clears all buffers for the current writer and causes
any buffered data to be written to the underlying device.
6 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
7 GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) 8 GetType Gets the Type of the current instance. (Inherited
from Object.)
9 InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
10 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.) 11 Synchronized Creates a thread-safe wrapper around the specified
TextWriter.
12 ToString Returns a String that represents the current Object. (Inherited from Object.)
13 Write Overloaded. Writes the given data type to a text stream.
14 WriteLine Overloaded. Writes some data as specified by the overloaded parameters, followed by a line
This program demonstrates about TextWriter Class: using System;
using System.IO; class TextRW {
static void Main() {
TextWriter stringWriter = new StringWriter(); using(TextWriter streamWriter = new StreamWriter("InvalidPathChars.txt")) { WriteText(stringWriter); WriteText(streamWriter); } TextReader stringReader = new StringReader(stringWriter.ToString()); using(TextReader streamReader = new StreamReader("InvalidPathChars.txt")) { ReadText(stringReader); ReadText(streamReader); } }
static void WriteText(TextWriter textWriter) {
textWriter.Write("Invalid file path characters are: "); textWriter.Write(Path.InvalidPathChars);
textWriter.Write('.'); }
static void ReadText(TextReader textReader) {
Console.WriteLine("From {0} - {1}",
textReader.GetType().Name, textReader.ReadToEnd()); }
File I/O Operations
.NET provides a FileStream class to read from, write to, open, and close files on a file system, as well as to manipulate other file-related operating system handles such as pipes, standard input, and standard output. You can specify read and write operations to be either synchronous or asynchronous. FileStream buffers input and output for better performance. FileStream objects support random access to files using the Seek method. Seek allows the read/write position to be moved to any position within the file.
Stream Reader Class
Implements a TextReader that reads characters from a byte stream in a particular encoding.
Public Fields:
S.No Name Description
1 Null A StreamReader object around an empty stream.
Public properties:
S.No Name Description
1 BaseStream Returns the underlying stream.
2 CurrentEncoding Gets the current character encoding that the current StreamReader object is using.
3 EndOfStream Gets a value that indicates whether the current stream position is at the end of the stream.
Public Methods:
S.No Name Description
1 Close Overridden. Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
2 CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
3 DiscardBufferedData Allows a StreamReader object to discard its current data.
4 Dispose Overloaded.
5 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.) 6 GetHashCode Serves as a hash function for a particular type.
GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
S.No Name Description
7 GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) 8 GetType Gets the Type of the current instance. (Inherited
from Object.)
9 InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
10 Peek Overridden. Returns the next available character but does not consume it.
11 Read Overloaded. Overridden. Reads the next character or next set of characters from the input stream. 12 ReadBlock Reads a maximum of count characters from the
current stream and writes the data to buffer, beginning at index. (Inherited from TextReader.) 13 ReadLine Overridden. Reads a line of characters from the
current stream and returns the data as a string. 14 ReadToEnd Overridden. Reads the stream from the current
position to the end of the stream.
15 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.) 16 Synchronized Creates a thread-safe wrapper around the specified
TextReader. (Inherited from TextReader.) 17 ToString Returns a String that represents the current Object.
(Inherited from Object.)
Stream Writer Class
Implements a TextWriter for writing characters to a stream in a particular encoding.
Public fields:
S.No Name Description
1 Null Provides a StreamWriter with no backing store that can be written to, but not read from.
Public properties:
S.No Name Description
1 AutoFlush Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to
StreamWriter.Write.
2 BaseStream Gets the underlying stream that interfaces with a backing store. 3 Encoding Overridden. Gets the Encoding in which the output is written.
S.No Name Description
4 FormatProvider Gets an object that controls formatting.(Inherited from TextWriter.) 5 NewLine Gets or sets the line terminator string used by the current
TextWriter.(Inherited from TextWriter.)
Public Methods:
S.No Name Description
1 Close Overridden. Closes the current StreamWriter object and the underlying stream.
2 CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
3 Dispose Overloaded.
4 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.) 5 Flush Overridden. Clears all buffers for the current writer
and causes any buffered data to be written to the underlying stream.
6 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
7 GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) 8 GetType Gets the Type of the current instance. (Inherited
from Object.)
9 InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
10 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.) 11 Synchronized Creates a thread-safe wrapper around the specified
TextWriter. (Inherited from TextWriter.)
12 ToString Returns a String that represents the current Object. (Inherited from Object.)
13 Write Overloaded. Writes to the stream.
14 WriteLine Overloaded. Writes some data as specified by the overloaded parameters, followed by a line
Summary
Text File: It is a file in which you can read or write the data using stream reader and stream writer.
Stream: Stream is used to either write or read in to file. It is broadly classified into the following
o readBuffer() o readLastBuffer() o writeBuffer() o writeLastBuffer()
Log File: It is a text file consisting of time stamped status and error messages, detailing the operational history of a given piece of software.
Stream Reader and Writer: It read and writes characters from a byte stream in a particular encoding.
Test Your Understanding
1. What is the purpose of stream writer? 2. What is the purpose of stream reader? 3. What you mean by log file?
Session 32: XML and .Net Framework
Learning Objectives
After completing the session, you will be able to:
Explain System.Xml assembly and its supported standards Identify how to avoid Name conflicts using namespaces Define XMLTextReader class
Identify how to validate the XML document by using of XMLvalidatingReader class Explain XMLTextWriter class and XMLDocument class
XML
The design goals for the XML classes in the .NET Framework are: High-productivity.
Standards-based. Multilingual support. Extensible.
Pluggable architecture.
Focused on performance, reliability, and scalability. Integration with ADO.NET.
The .NET Framework provides an opportunity to design an integrated suite of XML classes and also show innovation in the XML world. The XML classes provided are core elements of the .NET Framework. These classes provide an open, standards-compliant, interoperable solution to the challenges that developers face today. For more information on the suite of classes in XML in the .NET Framework, see the System.Xml, System.Xml.XPath, System.Xml.Xsl, and
System.Xml.Schema namespaces.
The goals of XML in .NET Framework are as follows: Compliance with the W3C standards. Extensibility.
Pluggable architecture. Performance.
Tight integration with ADO.NET.
Standards Compliance
Standards compliance means that the classes fully conform to the current W3C recommended standards of XML, Namespaces, XSLT, XPath, Schema, and the Document Object Model (DOM). Compliance ensures interoperability and eases application development across platforms.
Most notably, the XML classes in .NET Framework supports the W3C XML Schema Definition language (XSD) 1.0 recommendation. There are XML classes in the .NET Framework that provide validation, and an object model is available to build the XSD Schemas in memory. The fast, forward-only parser that can validate against XML Schemas and DTDs is called the XmlReader. The XmlReader is a compliant XML parser. The XmlSchemaSet class can be use to cache frequently used XML Schemas.
There are a set of XML classes in the .NET Framework that provide a Schema Object Model (SOM) that allows you to programmatically build and compile XSD schemas. The XmlSchema class represents an XSD schema. These schemas can be loaded and persisted using the XmlReader and XmlWriter classes.
The XmlDocument class implements the Document Object Model level 1 and level 2
recommendations and is tailored to the common design guidelines of the .NET Framework. For example, the method names are capitalized.
The XslCompiledTransform class conforms to the XSL Transformations (XSLT) Version 1.0 recommendation and the XML Path Language (XPath) 1.0 recommendation for transforming