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

C# Unit 4

The document provides an overview of C# strings, detailing their properties and methods for manipulation, such as concatenation, comparison, and substring extraction. It also covers exception handling in C#, including the use of try/catch blocks and user-defined exceptions, along with the concepts of checked and unchecked contexts for managing arithmetic overflow. Examples are provided throughout to illustrate the usage of various string methods and exception handling techniques.

Uploaded by

Ritu Sonwane
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)
17 views50 pages

C# Unit 4

The document provides an overview of C# strings, detailing their properties and methods for manipulation, such as concatenation, comparison, and substring extraction. It also covers exception handling in C#, including the use of try/catch blocks and user-defined exceptions, along with the concepts of checked and unchecked contexts for managing arithmetic overflow. Examples are provided throughout to illustrate the usage of various string methods and exception handling techniques.

Uploaded by

Ritu Sonwane
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/ 50

UNIT – IV

C# Strings
In C#, string is an object of System.String class that represent sequence of characters. Strings
are used for storing text.A string variable contains a collection of characters surrounded by
double quotes:We can perform many operations on strings such as concatenation, comparision,
getting substring, search, trim, replacement etc.

string vs String
In C#, string is keyword which is an alias for System.String class. That is why string and String
are equivalent. We are free to use any naming convention.
string s1 = "hello"; //creating string using string keyword
String s2 = "welcome"; //creating string using String class

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";

char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };


string s2 = new string(ch);

Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
Output:
hello
csharp
Some of the commonly used methods and properties of the string class include:
 Length: returns the length of the string
 IndexOf: finds the index of a specified character or substring in the string
 Substring: returns a substring of the string
 ToLower and ToUpper: convert the string to lowercase or uppercase
 Replace: replaces a specified character or substring with another character or substring
 Trim: removes any leading or trailing whitespace characters from the string
 Split: splits the string into an array of substrings based on a specified delimiter character
or substring

C# String Clone()
The C# Clone() method is used to clone a string object. It returns another copy of same data. The
return type of Clone() method is object.

Signature
public object Clone()

Parameters
It does not take any parameter.
Returns
It returns a reference.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = (String)s1.Clone();
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

Output:

Hello
Hello

String Compare()

The C# Compare() method is used to compare first string with second string lexicographically. It
returns an integer value.

If both strings are equal, it returns 0. If first string is greater than second string, it returns 1 else it
returns -1.

Rule
s1==s2 returns 0
s1>s2 returns 1
s1<s2 returns -1
Signatures

public static int Compare(String, String, StringComparison)


Parameters
first: first argument represents string which is to be compared with second string.
second: second argument represents string which is to be compared with first string.
Return
It returns an integer value.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
string s2 = "hello";
string s3 = "csharp";
string s4 = "mello";

Console.WriteLine(string.Compare(s1,s2));
Console.WriteLine(string.Compare(s2,s3));
Console.WriteLine(string.Compare(s3,s4));
}
}

Output:
0
1
-1

String CompareTo()

The C# CompareTo() method is used to compare String instance with a specified String object.
It indicates whether this String instance precedes, follows, or appears in the same position in the
sort order as the specified string or not.

Signature
public int CompareTo(String str)
public int CompareTo(Object)

Parameters
str: it is a string argument which is used to compare.
Return
It returns an integer value.

String CompareTo() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
string s2 = "hello";
string s3 = "csharp";
Console.WriteLine(s1.CompareTo(s2));
Console.WriteLine(s2.CompareTo(s3));
}
}

Output:
0

String Concat()

The C# Concat() method is used to concatenate multiple string objects. It returns concatenated
string. There are many overloaded methods of Concat().

Signature

public static string Concat(String, String)

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = "C#";
Console.WriteLine(string.Concat(s1,s2));
}
}

Output:

Hello C#

String Contains()
The C# Contains() method is used to return a value indicating whether the specified substring
occurs within this string or not. If the specified substring is found in this string, it returns true
otherwise false.

Signature

public bool Contains(String str)

Parameters

str: it is a string object which is used to check occurrence in the calling string.

Return

It returns boolean value either true or false.

Example

using System;

public class StringExample

{
public static void Main(string[] args)

string s1 = "Hello ";

string s2 = "He";

string s3 = "Hi";

Console.WriteLine(s1.Contains(s2));

Console.WriteLine(s1.Contains(s3));

Output:
True
False

Example:
string text = " Hello, world! ";
int length = text.Length; // length = 17
int index = text.IndexOf("world"); // index = 8
string subString = text.Substring(3, 7); // subString = "lo, wor"
string upperCaseText = text.ToUpper(); // upperCaseText = " HELLO, WORLD! "
string replacedText = text.Replace("world", "everyone"); // replaced Text = " Hello, everyone! "
string[] words = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
// words = { "Hello", "world!" }
string trimmedText = text.Trim(); // trimmedText = "Hello, world!"
String CompareTo()
The C# CompareTo() method is used to compare String instance with a specified String object. It
indicates whether this String instance precedes, follows, or appears in the same position in the
sort order as the specified string or not.

Signature
public int CompareTo(String str)
Parameters
str: it is a string argument which is used to compare.
Return
It returns an integer value.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
string s2 = "hello";
string s3 = "csharp";
Console.WriteLine(s1.CompareTo(s2));
Console.WriteLine(s2.CompareTo(s3));
}
}

Output:

0
1
String Copy()
The C# Copy() method is used to create a new instance of String with the same value as a
specified String. It is a static method of String class. Its return type is string.

Signature
public static string Copy(String str)
Parameter
str: it takes a string argument which is used to create a copy of specified string.

Return
It returns string object.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = string.Copy(s1);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

Output:

Hello
Hello

String CopyTo()
The C# CopyTo() method is used to copy a specified number of characters from the specified
position in the string. It copies the characters of this string into a char array.
Signature
public void CopyTo(int index, char[] ch, int start, int end)

Parameter
index: it is an integer type parameter. It is an index of string.

ch: it is a char type array.

start: it is start index of char type array.

end: it is end index of char type array.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#, How Are You?";
char[] ch = new char[15];
s1.CopyTo(10,ch,0,12);
Console.WriteLine(ch);
}
}

Output:

How Are You?

String EndsWith()
The C# EndsWith() method is used to check whether the specified string matches the end of this
string or not. If the specified string is found at the end of this string, it returns true otherwise
false.
Signature
public bool EndsWith(String str)

Parameters
str: it is a string object which is used to check the whether a specified string ends with it.
Return
It returns boolean value either true or false.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello";
string s2 = "llo";
string s3 = "C#";
Console.WriteLine(s1.EndsWith(s2));
Console.WriteLine(s1.EndsWith(s3));
}
}

Output:
True
False

String Equals()
The C# Equals() method is used to check whether two specified String objects have the same
value or not. If both strings have same value, it return true otherwise false.

In other words, it is used to compare two strings on the basis of content.

Signature
public bool Equals(String str)

str: it is a string object.


Return
It returns boolean value either true or false.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello";
string s2 = "Hello";
string s3 = "Bye";
Console.WriteLine(s1.Equals(s2));
Console.WriteLine(s1.Equals(s3));
}
}
Output:
True
False

String IndexOf()
The C# IndexOf() is used to get index of the specified character present in the string. It returns
index as an integer value.

Signature
public int IndexOf(Char ch)

Parameters
ch: it is a character type parameter.
Return
It returns an integer value.
C# String IndexOf() Method Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
int index = s1.IndexOf('e');
Console.WriteLine(index);
}
}

Output:

String Insert()
The C# Insert() method is used to insert the specified string at specified index number. The index
number starts from 0. After inserting the specified string, it returns a new modified string.
Signature
public string Insert(Int32 first, String second)
Parameters
first: It is used to pass as an index.
second: It is used to insert the given string at specified index.
Return
It returns a new modified string.

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
string s2 = s1.Insert(5,"-");
Console.WriteLine(s2);
}
}
Output:
Hello- C#

Exception
The errors which we are getting at the run time of the application are called an exception.
If any exception is coming into our application then the application is abnormally terminated.
The Application is not considered as a good application if any exception is coming and it is not
handled.
Every time when we are developing an application and it got successfully build without any
errors. Then this happens.

Exception Handling
Exception Handling in C# is a process to handle runtime errors. We perform exception handling
so that normal flow of the application can be maintained even after runtime errors.
In C#, exception is an event or object which is thrown at runtime. All exceptions the derived
from System.Exception class. It is a runtime error which can be handled. If we don't handle the
exception, it prints exception message and terminates the program.

Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed event
after exception.

C# Exception Classes
All the exception classes in C# are derived from System.Exception class.
Exception Description

System.DivideByZeroException handles the error generated by dividing a number with zero.

System.NullReferenceException handles the error generated by referencing the null object.

System.InvalidCastException handles the error generated by invalid typecasting.

System.IO.IOException handles the Input Output errors.

System.IndexOutOfRangeException handles attempting to access an array element that does not exist.

System.FieldAccessException handles the error generated by invalid private or protected field


access.

C# Exception Handling Keywords


In C#, we use 4 keywords to perform exception handling:

 try
 catch
 finally, and
 throw

try/catch

In C# programming, exception handling is performed by try/catch statement. The try block in


C# is used to place the code that may throw exception. The catch block is used to handled the
exception. The catch block must be preceded by try block.

Example without try/catch


using System;
public class ExExample
{
public static void Main(string[] args)
{
int a = 10;
int b = 0;
int x = a/b;
Console.WriteLine("Rest of the code");
}
}

Output:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

Example with try/catch


using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }

Console.WriteLine("Rest of the code");


}
}
Output:
System.DivideByZeroException: Attempted to divide by zero.
Rest of the code
finally
C# finally block is used to execute important code which is to be executed whether exception is
handled or not. It must be preceded by catch or try block.

Example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
Output:
System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code

User-Defined Exceptions
C# allows us to create user-defined or custom exception. It is used to make the meaningful
exception. To do this, we need to inherit Exception class.
Example
using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}

Output:
InvalidAgeException: Sorry, Age must be greater than 18
Rest of the code

Checked and Unchecked


C# provides checked and unchecked keyword to handle integral type exceptions. Checked and
unchecked keywords specify checked context and unchecked context respectively. In checked
context, arithmetic overflow raises an exception whereas, in an unchecked context, arithmetic
overflow is ignored and result is truncated.
Checked
The checked keyword is used to explicitly check overflow and conversion of integral type values
at compile time.

Let's first see an example that does not use checked keyword.

Example without using checked


using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}

Output:

-2147483647

See, the above program produces the wrong result and does not throw any overflow exception.

Checked Example using checked


This program throws an exception and stops program execution.
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.

Unchecked
The Unchecked keyword ignores the integral type arithmetic exceptions. It does not check
explicitly and produce result that may be truncated or wrong.

Example
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:
-2147483647

SystemException class
The SystemException is a predefined exception class in C#. It is used to handle system related
exceptions. It works as base class for system exception namespace. It has various child classes
like: ValidationException, ArgumentException, ArithmeticException, DataException,
StackOverflowException etc.

It consists of rich constructors, properties and methods that we have tabled


below.

Signature

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class SystemException : Exception

Example
This class can be used to handle exception of subclasses. Here, in the following program,
program throws an IndexOutOfRangeException that is subclass of SystemException class.
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
int[] arr = new int[5];
arr[10] = 25;
}
catch (SystemException e)
{
Console.WriteLine(e);
}
}
}
}

Output:
System.IndexOutOfRangeException: Index was outside the bounds of the array.

FileStream
C# FileStream class provides a stream for file operation. It can be used to perform synchronous
and asynchronous read and write operations. By the help of FileStream class, we can easily read
and write data into file.

Example: writing single byte into file


Let's see the simple example of FileStream class to write single byte of data into file. Here, we
are using OpenOrCreate file mode which can be used for read and write operations.

using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);//creating file stream
f.WriteByte(65);//writing byte into stream
f.Close();//closing stream
}
}
Output:
A

Example: writing multiple bytes into file


Let's see another example to write multiple bytes of data into file using loop.

using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
for (int i = 65; i <= 90; i++)
{
f.WriteByte((byte)i);
}
f.Close();
}
}

Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Example: reading all bytes from file


Let's see the example of FileStream class to read data from the file. Here, ReadByte() method of
FileStream class returns single byte. To all read all the bytes, you need to use loop.

using System;
using System.IO;
public class FileStreamExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
int i = 0;
while ((i = f.ReadByte()) != -1)
{
Console.Write((char)i);
}
f.Close();
}
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ

StreamWriter

C# StreamWriter class is used to write characters to a stream in specific encoding. It inherits


TextWriter class. It provides overloaded write() and writeln() methods to write data into file.

Example
Let's see a simple example of StreamWriter class which writes a single line of data into the file.
using System;
using System.IO;
public class StreamWriterExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\output.txt", FileMode.Create);
StreamWriter s = new StreamWriter(f);

s.WriteLine("hello c#");
s.Close();
f.Close();
Console.WriteLine("File created successfully...");
}
}
Output:

File created successfully...

Now open the file, you will see the text "hello c#" in output.txt file.

output.txt:

hello c#

StreamReader
C# StreamReader class is used to read string from the stream. It inherits TextReader class. It
provides Read() and ReadLine() methods to read data from the stream.
C# StreamReader example to read one line
Let's see the simple example of StreamReader class that reads a single line of data from the file.

using System;
using System.IO;
public class StreamReaderExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\output.txt", FileMode.OpenOrCreate);
StreamReader s = new StreamReader(f);
string line=s.ReadLine();
Console.WriteLine(line);
s.Close();
f.Close();
}
}

Output:
Hello C#
Example to read all lines
using System;
using System.IO;
public class StreamReaderExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\a.txt", FileMode.OpenOrCreate);
StreamReader s = new StreamReader(f);
string line = "";
while ((line = s.ReadLine()) != null)
{
Console.WriteLine(line);
}
s.Close();
f.Close();
}
}

Output:
Hello C#
this is file handling

TextWriter
C# TextWriter class is an abstract class. It is used to write text or sequential series of characters
into file. It is found in System.IO namespace.

Example
Let's see the simple example of TextWriter class to write two lines data.
using System;
using System.IO;
namespace TextWriterExample
{
class Program
{
static void Main(string[] args)
{
using (TextWriter writer = File.CreateText("e:\\f.txt"))
{
writer.WriteLine("Hello C#");
writer.WriteLine("C# File Handling ");
}
Console.WriteLine("Data written successfully...");
}
}
}

Output:

Data written successfully...

f.txt:

Hello C#
C# File Handling

TextReader
C# TextReader class is found in System.IO namespace. It represents a reader that can be used to
read text or sequential series of characters.

Example: Read All Data


Let's see the simple example of TextReader class that reads data till the end of file.
using System;
using System.IO;
namespace TextReaderExample
{
class Program
{
static void Main(string[] args)
{
using (TextReader tr = File.OpenText("e:\\f.txt"))
{
Console.WriteLine(tr.ReadToEnd());
}
}
}
}
Output:
Hello C#
C# File Handling

Example: Read One Line


Let's see the simple example of TextReader class that reads single line from the file.
using System;
using System.IO;
namespace TextReaderExample
{
class Program
{
static void Main(string[] args)
{
using (TextReader tr = File.OpenText("e:\\f.txt"))
{
Console.WriteLine(tr.ReadLine());
}
}
}
}

Output:

Hello C#

BinaryWriter
C# BinaryWriter class is used to write binary information into stream. It is found in System.IO
namespace. It also supports writing string in specific encoding.
Example
Let's see the simple example of BinaryWriter class which writes data into dat file.
using System;
using System.IO;
namespace BinaryWriterExample
{
class Program
{
static void Main(string[] args)
{
string fileName = "e:\\binaryfile.dat";
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(2.5);
writer.Write("this is string data");
writer.Write(true);
}
Console.WriteLine("Data written successfully...");
}
}
}

Output:

Data written successfully...

BinaryReader
C# BinaryReader class is used to read binary information from stream. It is found in System.IO
namespace. It also supports reading string in specific encoding.

Example
Let's see the simple example of BinaryReader class which reads data from dat file.
using System;
using System.IO;
namespace BinaryWriterExample
{
class Program
{
static void Main(string[] args)
{
WriteBinaryFile();
ReadBinaryFile();
Console.ReadKey();
}
static void WriteBinaryFile()
{
using (BinaryWriter writer = new BinaryWriter(File.Open("e:\\binaryfile.dat", FileMode.
Create)))
{

writer.Write(12.5);
writer.Write("this is string data");
writer.Write(true);
}
}
static void ReadBinaryFile()
{
using (BinaryReader reader = new BinaryReader(File.Open("e:\\binaryfile.dat", FileMod
e.Open)))
{
Console.WriteLine("Double Value : " + reader.ReadDouble());
Console.WriteLine("String Value : " + reader.ReadString());
Console.WriteLine("Boolean Value : " + reader.ReadBoolean());
}
}
}
}

Output:
Double Value : 12.5
String Value : this is string data
Boolean Value : true

StringWriter Class
This class is used to write and deal with string data rather than files. It is derived class of
TextWriter class. The string data written by StringWriter class is stored into StringBuilder.
The purpose of this class is to manipulate string and save result into the StringBuilder.
StringWriter Class Signature
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StringWriter : TextWriter

Example
In the following program, we are using StringWriter class to write string
information to the StringBuilder class. The StringReader class is used to read
written information to the StringBuilder.
using System;

using System.IO;
using System.Text;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
string text = "Sarojini Naidu Govt. PG College \n" +
"Shivaji Nagar \n" +
"Bhopal";
// Creating StringBuilder instance
StringBuilder sb = new StringBuilder();
// Passing StringBuilder instance into StringWriter
StringWriter writer = new StringWriter(sb);
// Writing data using StringWriter
writer.WriteLine(text);
writer.Flush();
// Closing writer connection
writer.Close();
// Creating StringReader instance and passing StringBuilder
StringReader reader = new StringReader(sb.ToString());
// Reading data
while (reader.Peek() > -1)
{
Console.WriteLine(reader.ReadLine());
}
}
}
}

Output:
Sarojini Naidu Govt. PG College
Shivaji Nagar
Bhopal

StringReader Class
StringReader class is used to read data written by the StringWriter class. It is subclass of
TextReader class. It enables us to read a string synchronously or asynchronously. It provides
constructors and methods to perform read operations.

Signature
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StringReader : TextReader

Example
In the following example, StringWriter class is used to write the string information and
StringReader class is used to read the string, written by the StringWriter class.
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
StringWriter str = new StringWriter();
str.WriteLine("Hello, this message is read by StringReader class");
str.Close();
// Creating StringReader instance and passing StringWriter
StringReader reader = new StringReader(str.ToString());
// Reading data
while (reader.Peek() > -1)
{
Console.WriteLine(reader.ReadLine());
}
}
}
}

Output:

Hello, this message is read by StringReader class

FileInfo Class
The FileInfo class is used to deal with file and its operations in C#. It provides properties and
methods that are used to create, delete and read file. It uses StreamWriter class to write data to
the file. It is a part of System.IO namespace.

Signature
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class FileInfo : FileSystemInfo

Example: Creating a File


using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file location
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Creating an empty file
file.Create();
Console.WriteLine("File is created Successfuly");
}catch(IOException e)
{
Console.WriteLine("Something went wrong: "+e);
}
}
}
}
Output:
File is created successfully

Example: writing to the file


using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file location
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Creating an file instance to write
StreamWriter sw = file.CreateText();
// Writing to the file
sw.WriteLine("This text is written to the file by using StreamWriter class.");
sw.Close();
}catch(IOException e)
{
Console.WriteLine("Something went wrong: "+e);
}
}
}
}

Output:
Example: Reading text from the file
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file to read
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Opening file to read
StreamReader sr = file.OpenText();
string data = "";
while ((data = sr.ReadLine()) != null)
{
Console.WriteLine(data);
}
}
catch (IOException e)
{
Console.WriteLine("Something went wrong: " + e);
}
}
}
}

Output:

C# DirectoryInfo Class
DirectoryInfo class is a part of System.IO namespace. It is used to create, delete and move
directory. It provides methods to perform operations related to directory and subdirectory. It is a
sealed class so, we cannot inherit it.

The DirectoryInfo class provides constructors, methods and properties that are listed below.

C# DirectoryInfo Syntax
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class DirectoryInfo : FileSystemInfo

C# DirectoryInfo Constructors
The following table contains the constructors for the DirectoryInfo class.
Constructor Description

DirectoryInfo(String) It is used to initialize a new instance of the DirectoryInfo class on the specified
path.

C# DirectoryInfo Properties
The following table contains the properties of the DirectoryInfo class.

Property Description

Attributes It is used to get or set the attributes for the current file or directory.

CreationTime It is used to get or set the creation time of the current file or directory.

CreationTimeUtc It is used to get or set creation time, in coordinated universal time (UTC).

Exists It is used to get a value indicating whether the directory exists.

Extension It is used to get the string representing the extension part of the file.

FullName It is used to get the full path of the directory.

LastAccessTime It is used to get or set the time the current file or directory was last accessed.

LastAccessTimeUtc It is used to get or set the time, in coordinated universal time (UTC) that the
current file or directory was last accessed.

LastWriteTime It is used to get or set the time when the current file or directory was last written.

LastWriteTimeUtc It is used to get or set the time, in coordinated universal time (UTC), when the
current file or directory was last written.

Name It is used to get the name of this DirectoryInfo instance.

Parent It is used to get the parent directory of a specified subdirectory.

Root It is used to get the root portion of the directory.


C# DirectoryInfo Methods
The following table contains the methods of the DirectoryInfo class.

Method Description

Create() It is used to create a directory.

Create(DirectorySecurity) It is used to create a directory using a DirectorySecurity object.

CreateObjRef(Type) It is used to create an object that contains all the relevant information
required to generate a proxy used to communicate with a remote
object.

CreateSubdirectory(String) It is used to create a subdirectory or subdirectories on the specified


path.

CreateSubdirectory(String,Direc It is used to create a subdirectory or subdirectories on the specified


torySecurity) path with the specified security.

Delete() It is used to delete this DirectoryInfo if it is empty.

Delete(Boolean) It is used to delete this instance of a DirectoryInfo, specifying


whether to delete subdirectories and files.

EnumerateDirectories() It returns an enumerable collection of directory information in the


current directory.

EnumerateFiles() It returns an enumerable collection of file information in the current


directory.

GetAccessControl() It is used to get a DirectorySecurity object that encapsulates the


access control list (ACL) entries for the directory.

GetDirectories() It returns the subdirectories of the current directory.

GetFiles() It returns a file list from the current directory.

GetType() It is used to get the Type of the current instance.


MoveTo(String) It is used to move a DirectoryInfo instance and its contents to a new
path.

Refresh() It is used to refresh the state of the object.

SetAccessControl(DirectorySec It is used to set access control list (ACL) entries described by a


urity) DirectorySecurity object.

ToString() It returns the original path that was passed by the user.

C# DirectoryInfo Example
In the following example, we are creating a javatpoint directory by specifying the
directory path.

using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
// Provide directory name with complete location.
DirectoryInfo directory = new DirectoryInfo(@"F:\javatpoint");
try
{
// Check, directory exist or not.
if (directory.Exists)
{
Console.WriteLine("Directory already exist.");
return;
}
// Creating a new directory.
directory.Create();
Console.WriteLine("The directory is created successfully.");
}
catch (Exception e)
{
Console.WriteLine("Directory not created: {0}", e.ToString());
}
}
}
}

Output:

The directory is created successfully.

In below screenshot, we can see that a directory is created.

The DirectoryInfo class also provides a delete method to delete created directory. In the
following program, we are deleting a directory that we created in previous program.
C# DirectoryInfo Example: Deleting Directory
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
// Providing directory name with complete location.
DirectoryInfo directory = new DirectoryInfo(@"F:\javatpoint");
try
{
// Deleting directory
directory.Delete();
Console.WriteLine("The directory is deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("Something went wrong: {0}", e.ToString());
}
}
}
}
Output:
The directory is deleted successfully.

It throws a System.IO.DirectoryNotFoundException exception if the specified directory not


present at the location.
C# Serialization
In C#, serialization is the process of converting object into byte stream so that it can be saved to
memory, file or database. The reverse process of serialization is called deserialization.
Serialization is internally used in remote applications.

C# SerializableAttribute
To serialize the object, you need to apply SerializableAttribute attribute to the type. If you don't
apply SerializableAttribute attribute to the type, SerializationException exception is thrown at
runtime.

C# Serialization example
Let's see the simple example of serialization in C# where we are serializing the object of Student
class. Here, we are going to use BinaryFormatter.Serialize(stream, reference) method to
serialize the object.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
{
int rollno;
string name;
public Student(int rollno, string name)
{
this.rollno = rollno;
this.name = name;
}
}
public class SerializeExample
{
public static void Main(string[] args)
{
FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
BinaryFormatter formatter=new BinaryFormatter();

Student s = new Student(101, "sonu");


formatter.Serialize(stream, s);
stream.Close();
}
}
sss.txt:
JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Student
rollnoname e sonu
As you can see, the serialized data is stored in the file. To get the data, you need to perform
deserialization.

C# Deserialization
In C# programming, deserialization is the reverse process of serialization. It means you can read
the object from byte stream. Here, we are going to
use BinaryFormatter.Deserialize(stream) method to deserialize the stream.

C# Deserialization Example
Let's see the simple example of deserialization in C#.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
{
public int rollno;
public string name;
public Student(int rollno, string name)
{
this.rollno = rollno;
this.name = name;
}
}
public class DeserializeExample
{
public static void Main(string[] args)
{
FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
BinaryFormatter formatter=new BinaryFormatter();

Student s=(Student)formatter.Deserialize(stream);
Console.WriteLine("Rollno: " + s.rollno);
Console.WriteLine("Name: " + s.name);

stream.Close();
}
}
Output:
Rollno: 101
Name: sonu
C# System.IO Namespace
The System.IO namespace consists of IO related classes, structures, delegates and enumerations.
These classes can be used to reads and write data to files or data streams. It also contains classes
for file and directory support.
C# System.IO Namespace Classes
Following are the classes reside into System.IO namespace.

Class Description

BinaryReader It is used to read primitive data types as binary values in a specific encoding.

BinaryWriter It is used to write primitive types in binary to a stream.

BufferedStream It is used to add a buffering layer to read and write operations on another
stream. It is a sealed class.

Directory It is used to expose static methods for creating, moving and enumerating
through directories and subdirectories. It is a sealed class.

DirectoryInfo It is used to expose instance methods for creating, moving and enumerating
through directories and subdirectories. It is a sealed class.

DirectoryNotFoundE It is used to handle exception related to the file or directory cannot be found.
xception

DriveInfo It is used to access the information on a drive.

DriveNotFoundExce It is used to handle drive not found exception.


ption

EndOfStreamExcept It is used to handle end of stream exception.


ion

ErrorEventArgs It provides data for the FileSystemWatcher.Error event.


File This class provides static methods for the creation, copying, deletion, moving
and opening of a single file.

FileFormatException It is used to handle file format exception.

FileInfo It is used to provide properties and instance methods for the creation,
copying, deletion, moving and opening of files.

FileLoadException It is used to handle file load exception.

FileNotFoundExcept It is used to handle file load exception.


ion

FileNotFoundExcept It is used to handle file not found exception.


ion

FileStream It provides a Stream for a file, supporting both synchronous and


asynchronous read and write operations.

FileSystemEventArg It provides data for the directory events.


s

FileSystemInfo It provides the base class for both FileInfo and DirectoryInfo objects.

FileSystemWatcher It listens to the file system change notifications and raises events when a
directory or file in a directory, changes.

InternalBufferOverfl This class is used to handle internal buffer overflow exception.


owException

InvalidDataExceptio It is used to handle invalid data exception.


n

IODescriptionAttrib It sets the description visual designers can display when referencing an event,
ute extender or property.

IOException It is an exception class that handles I/O errors.


MemoryStream It is used to create a stream whose backing store is memory.

Path It performs operations on String instances that contain file or directory path
information.

PathTooLongExcept It is an exception class and used to handle path too long exception.
ion

PipeException This exception class is used to handle pipe related exception.

RenamedEventArgs It is used to provide data for the Renamed event.

Stream It is used to provide a generic view of a sequence of bytes. It is an abstract


class.

StreamReader It is used to implement a TextReader that reads characters from a byte stream.

StringReader It is used to implement a TextReader that reads from a string.

StringWriter It is used to implement a TextWriter for writing information to a string. The


information is stored in an underlying StringBuilder.

TextReader This class is used to represent a reader that can read a sequential series of
characters.

TextWriter This class is used to represent a writer that can write a sequential series of
characters.

UnmanagedMemory It is used to provide random access to unmanaged blocks of memory from


Accessor managed code.

UnmanagedMemory It is used to get access to unmanaged blocks of memory from managed code.
Stream

System.IO Namespace Structures


Following are the structures reside into the System.IO Namespace.
Structure Description

WaitForChangedResult It contains information on the change that occurred.

System.IO Namespace Delegates


The System.IO Namespace contains the following delegates.

Delegates Description

ErrorEventHandler It represents the method that will handle the Error event of a
FileSystemWatcher object.

FileSystemEventHandler It represents the method that will handle the Changed, Created or Deleted
event of a FileSystemWatcher class.

RenamedEventHandler It represents the method that will handle the renamed event of a
FileSystemWatcher class.

System.IO Namespace Enumerations


The following table contains the enumerations reside into the System.IO namespace.

Enumeration Description

DriveType It is used to define constants for drive types including CDRom, Fixed,
Network etc.

FileAccess It is used to define constants for read, write or read/write access to a file.

FileAttributes It is used to provide attributes for files and directories.

FileMode It is used to specify how the operating system should open a file.

FileOptions It is used to represents advanced options for creating a FileStream object.

FileShare It is used to contain constants for controlling the kind of access other
FileStream objects can have to the same file.

HandleInheritability It specifies whether the underlying handle is inheritable by child processes.

NotifyFilters It is used to specify changes to watch for in a file or folder.

SearchOption It is used to specify whether to search the current directory or the current
directory and all subdirectories.

SeekOrigin It is used to specify the position in a stream to use for seeking.

WatcherChangeTypes It changes that might occur to a file or directory.

You might also like