C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

TextReader and TextWriter in C#

Reading and writing text data in C#, the System.IO namespace provides abstract classes called TextReader and TextWriter. They offer a standard interface and a collection of techniques for reading and writing characters, strings, and lines of text from various sources.

TextReader:

The System.IO namespace contains an abstract class called TextReader. It serves as the fundamental class for character data reading from different sources. It offers a standard interface for reading text data, making it simple to work consistently with various input sources like files, streams, or strings.

  • An abstract class called TextReader is used to read character data from a source. It offers ways to read individual characters, lines, and text blocks.
  •  Here are a few TextReader techniques that are frequently used:
MethodDescription
Read()Retrieves the next character from the input source and returns the Unicode value of that character as an integer. If the input source's end is reached, it returns -1.
Read(char[] buffer, int index, int count) readsReads a predetermined number of characters from the input source into the character array given and returns the number of characters read.
ReadLine()A line of characters is read from the input source and returned as a string by the function. If the input source's end is reached, the function returns null.
Peek()Without actually reading the character from the input source or stream, it returns the next character that is accessible.
Close()Exits the TextReader and releases all associated system resources.
Dispose()releases any resources held by the TextReader object and disposes of the object. Typically, when TextReader is used in a using statement, it is called automatically.
ReadToEnd()To read all characters from the current location to the end of the text reader, use the ReadToEnd() method. It returns all characters as a single string. This entails repeating a string including all characters from the present location to the text reader's finish.
Synchronised()Synchronized () wrap the provided TextReader in a thread-safe container.

Example:

using System;

using System.IO;

class Program5

{

    static void Main()

    {

        string filePath = @"D:\example.txt";

        TextReader reader = null;

        try

        {

            Reader = File.OpenText(filePath);

            string line;

            while ((line = reader.ReadLine()) != null)

            {

                Console.WriteLine(line);

            }

        }

        catch (FileNotFoundException)

        {

            Console.WriteLine(“File not found”);

        }

        catch (IOException)

        {

            Console.WriteLine(“An error occurred while reading the file.”);

        }

        finally

        {

            if (reader!= null)

                reader.Close();

        }

    }

}

Output:

TextReader and TextWriter in C#

Note: For these program to read correctly, please ensure that these file ”D:example.txt” exists and has some data. If not, you will receive the message “File not found”.

  • A text file called "D:example.txt" contains the C# program that reads and displays the contents line by line.
  • The correct error messages will be displayed if the File cannot be found or a reading problem occurs.

The "example.txt" File's contents, presuming the File is present and can be read, will be the program's output. The terminal will display each line of the File.

TextWriter in C#

The TextWriter class in C# is an abstract base class for writing character data to a stream. It is a component of the System.IO namespace. Writing text to a file, memory buffer, and another output destination can be replaced with an a higher-level abstraction.

  • To the underlying output stream, this class offers methods for writing single characters, strings, and character arrays.
MethodsDescription
WriteLineAsync(string s)This method encapsulates the supplied TextWriter in a thread-safe container. It ensures several threads can write to the same stream without encountering problems.
Close()the current writer and releasing any system resources it uses are accomplished via the Close() method.
dispose()The TextWriter object's resources are released by the method. After the writing is finished, it is advised to call Dispose or utilize the using statement to clear up resources appropriately.
Flush()Where all buffered data is to be written to the underlying device and clears all buffers for the current writer.
Write(char ch)Use this function to add one character at a time to the text stream.
WriteAsync(char ch)Use the function to add the character to the text stream asynchronously when you don't want the program to wait for the write operation to finish.
Write(string s)Use the Write(string s) function to add a string to the text stream.
WriteLine()A line terminator is added to the text stream using the WriteLine() function. Depending on the platform, it prints a new line character or a string of carriage return and line feed characters.
WriteLineAsync(string s)This function is used to write the string and a line terminator asynchronously.

Example:

using System;

using System.IO;

class Program6

{

    static void Main()

    {

        string filePath = "D:\examp.txt";

        try

        {

            using (StreamWriter writer = new StreamWriter(filePath))

            {

                writer.Write("welcome, ");

                writer.WriteLine("Tutorials and example");

                writer.WriteLine("Happy learning");

            }

            Console.WriteLine("Text written to the file");

        }

        Catch (Exception ex)

        {

            Console.WriteLine("Error: " + ex.Message);

        }

    }

}

Output:

You should locate a file called "examp.txt" in the "D:" directory after this program has been compiled. Its contents are as follows:

TextReader and TextWriter in C# TextReader and TextWriter in C#

 C# program that uses the StreamWriter class is write text to a file. The program must write the provided text into a file called "examp.txt" in the "D:" directory.