SlideShare a Scribd company logo
1 of 25
Download to read offline
C#Zone
Week 9(according to IUB outline):-
---------------------------------------------------------------------------------
9. Building .NET-based Applications with C#
1. Examining Microsoft .NET Framework class library
2. The Object Browser
3. Overriding Methods from System.Object class
4. Formatting Strings, Numbers, Currency and date values.
5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream
6. Serialization and De-serialization.
---------------------------------------------------------------------------------
Any issue:umarfarooqworld@outlook.com
>>Welcome Back<<
Ref: C#Corner Pick “N” Share :C#Zone
2 | P a g e “A room without books is like a body without a soul”
1. Examining Microsoft .NET Framework class library
The .NET Framework class library is a library of classes, interfaces, and value types
that provide access to system functionality. It is the foundation on which .NET
Framework applications, components, and controls are built. The namespaces and
namespace categories in the class library are listed in the following table and
documented in detail in this reference. The namespaces and categories are listed by
usage, with the most frequently used namespaces appearing first.
There are Thousands of .NET Framework class libraries and some is mentioned
below:
Namespaces
Namespace Description
System
The System namespace contains fundamental classes and base classes that define commonly-
used Value and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
System.Collections The System.Collections namespaces contain types that define various standard, specialized,
and generic collection objects.
2. Using the Object Browser
Visual C# 2008 includes a useful tool that enables you to easily view members (properties,
methods, and events) of all the objects in a project: the Object Browser (see Figure 3.10).
This is useful when dealing with objects that aren’t well documented because it enables you
to see all the members an object supports. To view the Object Browser, choose View, Other
Windows, Object Browser from the menu.
Ref: C#Corner Pick “N” Share :C#Zone
3 | P a g e “A room without books is like a body without a soul”
Figure 3.10. The Object Browser enables you to view all properties and methods of
an object.
The Browse drop-down list in the upper-left corner of the Object Browser is used to
determine the browsing scope. You can choose My Solution to view only the objects
referenced in the active solution, or you can choose All Components to view all possible
objects. You can customize the object set by clicking the drop-down arrow next to the
Object Browser Settings button to the far right of the Browse drop-down list. I
don’t recommend changing the custom object setting until you have some experience using
Visual C# objects as well as experience using the Object Browser.
The top-level nodes (each item in the tree is referred to as a node) in the Objects tree are
libraries. Libraries are usually DLL or EXE files on your computer that contain one or more
objects. To view the objects within a library, simply expand the library node. As you select
objects within a library, the list to the right of the Objects tree shows information regarding
the members of the selected object (refer to Figure 3.10). For even more detailed
information, click a member in the list on the right, and the Object Browser shows
information about the member in the area below the two lists.
Ref: C#Corner Pick “N” Share :C#Zone
4 | P a g e “A room without books is like a body without a soul”
3. Overriding Methods from System.Object class
Introduction:
Let us start by creating a new class and we will leave it with out any methods.
public class Employee
{
}
In the next step we will try to use our class, we will find that our Employee class contains 4 methods
which are (Equals, GetHashCode, GetType, and ToString).
The question now, from where these four methods come from?
The answer is easy: any data type in the .Net inherits implicitly from the Object class which defines a
common set of members supported by every type in the .NET, so when we create our new class
Employee it inherits from the Object class.
The Object base class defines some members that are virtual so it allows us to redefine the default
implementation of these members.
These virtual members give you a good work, but in some cases you will need a new
implementation of these methods to fit your class functionality.
In the next section we will see how to use the default implementation of the Object class virtual
methods and then we will try to redefine it by using override keyword to give it a new behavior.
Ref: C#Corner Pick “N” Share :C#Zone
5 | P a g e “A room without books is like a body without a soul”
ToString() Method:
The ToString() method gives you a textual representation of the current state of the object.
Example:
namespace UsingObjectClass
{
public class Employee
{
string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
int age;
public int Age
{
get { return age; }
set { age = value; }
}
string employeeID;
public string EmployeeID
{
get { return employeeID; }
set { employeeID = value; }
}
}
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
string s = emp1.ToString();
Console.WriteLine(s);
}
}
}
Ref: C#Corner Pick “N” Share :C#Zone
6 | P a g e “A room without books is like a body without a soul”
The result:
As you can see the returned string is the name of the Employee Type (UsingObjectClass.Employee).
What if we want to use the ToString() method to show the current employee data (First Name, Last
Name, and Age).
All we need to do is to override the ToString() Method to give it a new behavior, so in our case we will
redefine it to show the Employee data instead of the name of the object type.
Overriding ToString() Method:
The first step is to use the override keyword to override the method and then we will redefine its
behavior.
Example:
public class Employee
{
....
//Overriding ToString() method
public override string ToString()
{
string s = "First Name: " + firstName + " , " + " last Name: " + lastName + " , " +"and Age: " +
age;
return s;
}
}
Trying the new behavior of the ToString() method:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
string s = emp1.ToString();
Console.WriteLine(s);
Ref: C#Corner Pick “N” Share :C#Zone
7 | P a g e “A room without books is like a body without a soul”
The result:
As you can see we now have a good text representation of our object.
We can use also StringBuilder in our ToString() method as follow:
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("First Name: {0}, Last Name: {1}, and Age: {2}", firstName, lastName, age);
return sb.ToString();
}
Equals() Method:
Equals() method is used to compare two objects and it returns a true if these objects point to the same
values on the heap and returns false if not.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
Employee emp2 = emp1;
We now have two objects that point to the same value on the heap, so if we tried to use Equals()
method it will return true.
//this will return True.
emp1.Equals(emp2);
Now we will create two objects each one has its own value on the heap, so when we use Equals()
method it will return False.
Employee emp3 = new Employee();
emp3.FirstName = "Amr";
emp3.LastName = "Ashush";
emp3.Age = 40;
emp3.EmployeeID = "123A";
Ref: C#Corner Pick “N” Share :C#Zone
8 | P a g e “A room without books is like a body without a soul”
Employee emp4 = new Employee();
emp4.FirstName = "Amr";
emp4.LastName = "Ashush";
emp4.Age = 23;
emp4.EmployeeID = "123A";
//this will return False.
emp3.Equals(emp4);
Overriding Equals() Method:
Consider that we want to compare two objects but we do not want to know if these objects pointing to
the same value in the heap, all we need to know that if these two objects have the same data like
(First Name, and Last Name) for example.
Example:
//Overriding Equals() method
public override bool Equals(object obj)
{
if (obj != null && obj is Employee)
{
Employee emp = (Employee)obj;
if (emp.firstName == this.firstName &&
emp.lastName == this.lastName &&
emp.employeeID == this.employeeID)
return true;
}
return false;
}
Now when we try to use the Equals() method it will compare the firstName, lastName, and employeeID
of the two objects and it will return true if these value are the same and false if not.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
emp1.EmployeeID = "123A";
Employee emp2 = new Employee();
emp2.FirstName = "Amr";
emp2.LastName = "Ashush";
emp2.Age = 23;
emp2.EmployeeID = "123A";
//this will return True.
emp1.Equals(emp2);
If we have two objects with different data Equals method will return false.
Employee emp3 = new Employee();
emp3.FirstName = "Jack";
emp3.LastName = "Baher";
emp3.Age = 40;
emp3.EmployeeID = "1254B";
Ref: C#Corner Pick “N” Share :C#Zone
9 | P a g e “A room without books is like a body without a soul”
Employee emp4 = new Employee();
emp4.FirstName = "James";
emp4.LastName = "Bond";
emp4.Age = 23;
emp4.EmployeeID = "007";
//this will return False.
emp3.Equals(emp4);
GetHashCode() Method:
The GetHashCode() method is used to return a numerical value that identefies an object based on its
internal data.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = new Employee();
emp2.FirstName = "Ali";
emp2.LastName = "Hashmi";
emp2.Age = 23;
emp2.EmployeeID = "125";
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:
emp 1 hash code: 45653674
emp 2 hash code: 41149443
As you can see, instead of the two objects have the same data, each one have different hash code
because each object points to a different place on the heap.
So if we create two objects that point to the same value, when we call GetHashCode() method from
any one we will get the same hash code.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = emp1;
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:
emp 1 hash code: 45653674
emp 2 hash code: 45653674
Ref: C#Corner Pick “N” Share :C#Zone
10 | P a g e “A room without books is like a body without a soul”
Overriding GetHashCode() Method:
We need to override GetHashCode() method so if we have two objects with identical data we will
obtain the same hash code.
The String class has its own implementation of GetHashCode() method based on the string's character
data.
We can use the string that return from the overriden ToString() method and use it to call
GetHashCode() method. So if we have two objects with the same First Name, Last Name, and Age we
will obtain the same hash code.
//Overriding the GetHashCode method
public override int GetHashCode()
{
return ToString().GetHashCode();
}
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = new Employee();
emp2.FirstName = "Numan";
emp2.LastName = "Ashraf";
emp2.Age = 23;
emp2.EmployeeID = "125";
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:(the same hash code)
emp 1 hash code: -1503318716
emp 2 hash code: -1503318716
As you can see we get the same hash code although we have two object that are point to different
values on the heap.
Another option is to identify a string field that should be unique among objects and then return its hash
code.
In our case EmployeeID suould be unique so if we have two object with the same EmployeeID we will
get the same hash code.
//Overriding the GetHashCode method
public override int GetHashCode()
{
return EmployeeID.GetHashCode();
}
Note: Overriding GetHashCode() method only useful when you want to store your object in hash-
based collection such as Hashtable beacause the Hashtable type calles the Equals() and GetHashCode()
methods of the contained objects under the hood to determine the correct object to return to the
caller. and the Object class has no idea about the data on its subclasses.
Ref: C#Corner Pick “N” Share :C#Zone
11 | P a g e “A room without books is like a body without a soul”
4. Formatting Strings, Numbers, Currency and date values.
The Syntax of the String.Format() Method
The general syntax of the String.Format() method is as follows:
String.Format("format string", arg1, arg2, .... );
The format string is the string into which the values will be placed. Within this string
are place holders which indicate the location of each value within the string. Place holders
take the form of braces surrounding a number indicating the corresponding argument to be
substituted for the place holder. Following on from the format string is a comma separated
list of arguments. There must be an argument for each of the place holders.
A Simple C# String Format Example
The following code fragment demonstrates a very simple use of the String.Format() method:
string newString;
newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");
System.Console.WriteLine (newString);
When run, the above code will result in the following output:
There are 2 cats in my house and no dogs
Let's quickly review the String.Format() method call. The format string contains 3 place holders
indicated by {0}, {1} and {2}. Following the format string are the arguments to be used in each
place holder. For example, {0} is replaced by the first argument (the number 2), the {1} by the
second argument (the string "house") and so on.
Ref: C#Corner Pick “N” Share :C#Zone
12 | P a g e “A room without books is like a body without a soul”
Formatting Dates and Times in C#
There are number of techniques available for extracting and displaying dates and times in
particular formats. Output may be configured using a small number of predefined formatting
methods or customized with an almost infinite number of variations using the ToString()
method.
The basic formatting methods operate as follows:
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
System.Console.WriteLine(meetingAppt.ToLongDateString()); // Monday, September 22, 2008
System.Console.WriteLine(meetingAppt.ToShortDateString()); // 9/22/2008
System.Console.WriteLine(meetingAppt.ToShortTimeString()); // 2:30 PM
If the above prepackaged formatting methods do not provide the required output, a formidable
variety of custom formats may be constructing using the ToString() method.
The ToString() method takes as an argument a format string which specifies precisely how the
date and time is to be displayed. The following example shows a few of this formats in action.
The subsequent table lists all the possible format variables which may be used:
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
System.Console.WriteLine(meetingAppt.ToString("MM/dd/yy")); // 09/22/08
System.Console.WriteLine(meetingAppt.ToString("MM - dd - yyyy")); // 09 - 22 - 2008
System.Console.WriteLine(meetingAppt.ToString("ddd dd MMM yyyy")); // Mon 22 Sep 2008
System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // Monday September 22 2008
The full list of format patterns support by the ToString() method of the C# DateTime class is as
follows:
Format
Specifier
Description
d The day of the month. Single-digit days will not have a leading zero.
dd The day of the month. Single-digit days will have a leading zero.
ddd
The abbreviated name of the day of the week, as defined in
AbbreviatedDayNames.
dddd The full name of the day of the week, as defined in DayNames.
M The numeric month. Single-digit months will not have a leading zero.
MM The numeric month. Single-digit months will have a leading zero.
MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames.
MMMM The full name of the month, as defined in MonthNames.
Ref: C#Corner Pick “N” Share :C#Zone
13 | P a g e “A room without books is like a body without a soul”
Currency
In this article we will learn how to display a number in its currency format with respect to a
country. When we want to display a number in its respective country's currency format, we
format the string in the currency format and get the currency symbol of a specific country
using the "CultureInfo" class available in .Net. To use the CultureInfo class, we need to
include the "System.Globalization" Namespace in our program.
The "C" format specifier converts a number to a string that represents a currency amount.
The precision specifier indicates the desired number of decimal places in the result string. If
the precision specifier is omitted then the default precision is used (the default value is 2).
If the value to be formatted has more than the specified or the default number of decimal
places then the fractional value is rounded in the result string. If the value to the right of
the number of the specified decimal places is 5 or greater then the last digit in the result
string is rounded away from zero.
Here is code showing how to convert a number to its corresponding currency format for a respective country:
using System;
using System.Globalization;
namespace CurrencyFormatter
{
class Program
{
static void Main(string[] args)
{
double value = 5623345.6789;
//For Current Culture
Console.WriteLine("n--------- Displaying Currency in Current Culture ---------------n");
// By default, single letter C displays currency upto two decimal digits
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
// C2 displays currency upto two digits
Console.WriteLine(value.ToString("C2", CultureInfo.CurrentCulture));
// C3 displays currency upto three digits
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
// C4 displays currency upto four digits
Console.WriteLine(value.ToString("C4", CultureInfo.CurrentCulture));
// C5 displays currency upto five digits
Console.WriteLine(value.ToString("C5", CultureInfo.CurrentCulture));
Ref: C#Corner Pick “N” Share :C#Zone
14 | P a g e “A room without books is like a body without a soul”
//For Japan
Console.WriteLine("n--------- Dispalying Currency for Japan ---------------n");
Console.WriteLine(value.ToString("C", CultureInfo.CreateSpecificCulture("ja-JP")));
//For Denmark
Console.WriteLine("n--------- Dispalying Currency for Denmark ---------------n");
Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("da-DK")));
//For India
Console.WriteLine("n--------- Dispalying Currency for India ---------------n");
Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("en-IN")));
Console.Read();
}
}
}
Ref: C#Corner Pick “N” Share :C#Zone
15 | P a g e “A room without books is like a body without a soul”
Numbers
Number of time the end user / client require to display numeric data in different format. In this post I am going
to discuss about the various type of the custom format that provided by C#.net to achieve requirement. Here I
am going to discuss each format one by one..
"0" Custom Specifier
ToString("00000") - format put the leading 0 when number get display if digits in number less than the number
of zero specified. when the below code is get executed output display 01234 because the number of digit less
than the number of zero.
double value;
value = 1234;
Console.WriteLine("Format 1: " + value.ToString("00000"));
Console.WriteLine();
ToString("00.00") - format do same thing as above replace zero if the number digit less , but the zero after
decimal point allows to display digit equals number of zero after decimal if the number of digit less than display
zero in place of that. output of the following code is 01.24 i.e only 2 digit allowed after decimal point. Note : -
decimal point is display as per specified culture.
value = 1.235;
Console.WriteLine("Format 2: " + value.ToString("00.00",CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0") - format cause to display comma between number. here when the following code is get
executed , is get display after every three digit 1,234,567,890. Note : - in this comma get replace by the culture.
value = 1234567890;
Console.WriteLine("Format 3: " + value.ToString("0,0",CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0.0") - format is combination of above format.
value = 1234567890.123456;
Console.WriteLine("Format 4: " + value.ToString("0,0.0",CultureInfo.InvariantCulture));
Console.WriteLine();
Output
Ref: C#Corner Pick “N” Share :C#Zone
16 | P a g e “A room without books is like a body without a soul”
5. Using Streams and Files: Read and Write both Binary and
Text Files, Using FileStream
Introduction
In memory, objects cease to exist when a program ends. But files exist until deletion. With files we persist data.
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for
reading or writing, it becomes a stream. The stream is basically a sequence of bytes passing through the
communication path. There are two main streams, the input stream and the output stream.
The input stream is used for reading data from a file (read operation) and the output stream is used for writing
into the file (write operation). We handle them with types in System.IO.
Various Types of C# I/O Classes
The System.IO namespace has various classes for performing various operation with files, like creating and
deleting files, reading from or writing to a file, closing a file and so on.
Some important classes are as follows:
I/O Class Description
FileStream Used to read from and write to any location in a file
BinaryReader Reads primitive data from a binary stream
BinaryWriter Writes primitive data in binary format
File Use for manipulating files
StreamReader Used for reading characters from a byte stream
StreamWriter Is used for writing characters to a stream
StringReader Is used for reading from a string buffer
StringWriter Is used for writing into a string buffer
Directory Helps in manipulating a directory structure
DirectoryInfo Used for performing operations on directories
Now we see examples of some important I/O class and examine the outputs.
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class
derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an
existing file. The syntax for creating a FileStream object is as follows:
1. FileStream <object_name> = new FileStream( <file_name>,<FileMode Enumerator>, <FileAccess Enumerat
or>, <FileShare Enumerator>);
For example, create a FileStream object F for reading a file named Example.txt as:
1. FileStream My_File = new FileStream("Example.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare
.ReadWrite);
Ref: C#Corner Pick “N” Share :C#Zone
17 | P a g e “A room without books is like a body without a soul”
Now we see the meaning of each parameter.
FileMode
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator
are:
Mode Description
Append It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist
Create It creates a new file. If file is already exist then it will overrite that file
CreateNew It will also use to create a new file If the file is already exist then it will throw an Exception
Open It opens an existing file
OpenOrCreate
It specifies to the operating system that it should open a file if it exists, otherwise it should create a new
file
Truncate It opens an existing file and truncates its size to zero bytes
FileAccess
The FileAccess enumerator defines the kind of task to do with the file.
AccessMode Description
Read Data can be write from file
Write Data can be write written to the file
ReadWrite Data can be written to and read from the file
FileShare
This enumerator applies the type of permission for sharing.
SharingMode Description
Inheritable It allows a file handle to pass inheritance to the child processes
None It declines sharing of the current file
Read It allows opening the file for reading
ReadWrite It allows opening the file for reading and writing
Write It allows opening the file for writing
Example
The following program shows the use of the FileStream class:
Ref: C#Corner Pick “N” Share :C#Zone
18 | P a g e “A room without books is like a body without a soul”
Stream Reader and Stream Writer
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These
classes inherit from the abstract base class Stream that supports reading and writing bytes into a file stream.
The StreamReader Class
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for
reading series of characters. The following table describes some of the commonly used methods of the
StreamReader class:
Method Name Description
public override void
Close()
It closes the StreamReader object and the underlying stream and releases any system resources
associated with the reader.
public override int
Peek()
Returns the next available character but does not consume it
public override int
Read()
Reads the next character from the input stream and advances the character position by one
character
The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents a writer that can write a
series of characters.
The following table shows some of the most commonly used methods of this class:
Method Description
public override void Close() Closes the current StreamWriter object and the underlying stream
public override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to
the underlying stream
public virtual void Write(bool
value)
Writes the text representation of a Boolean value to the text string or stream.
(Inherited from TextWriter.)
public override void Write( char
value )
Writes a character to the stream
public virtual void Write( decimal
value )
Writes the text representation of a decimal value to the text string or stream
public virtual void Write( double
value )
Writes the text representation of an 8-byte floating-point value to the text string or
stream
public virtual void Write( int
value )
Writes the text representation of a 4-byte signed integer to the text string or stream
public override void Write( string
value )
Writes a string to the stream
public virtual void WriteLine() Writes a line terminator to the text string or stream
Ref: C#Corner Pick “N” Share :C#Zone
19 | P a g e “A room without books is like a body without a soul”
Example
The following example shows writing text data into a file using the StreamWriter class:
Binary Reader and Binary Writer
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader Class
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing
a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class:
Method Description
public override void
Close()
It closes the BinaryReader object and the underlying stream
public virtual int Read()
Reads the characters from the underlying stream and advances the current position of the
stream
public virtual bool
ReadBoolean()
Reads a Boolean value from the current stream and advances the current position of the
stream by one byte
public virtual char
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
public virtual char[]
ReadChars( int count )
Reads the specified number of 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
public virtual string
ReadString()
Reads a string from the current stream. The string is prefixed with the length, encoded as an
integer seven bits at a time
Ref: C#Corner Pick “N” Share :C#Zone
20 | P a g e “A room without books is like a body without a soul”
The BinaryWriter Class
The BinaryWriter class writes binary data to a stream. A BinaryWriter object is created by passing a FileStream
object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class:
Method Description
public override void
Close()
It closes the BinaryWriter object and the underlying stream
public virtual long Seek(
int offset, SeekOrigin
origin )
Sets the position within the current stream
public virtual void Write(
byte[] buffer )
Writes a byte array to the underlying stream
public virtual void Write(
char ch )
Writes a Unicode character to the current stream and advances the current position of the
stream in accordance with the Encoding used and the specific characters being written to
the stream
public virtual void Write(
char[] chars )
Writes a character array to the current stream and advances the current position of the
stream in accordance with the Encoding used and the specific characters being written to
the stream
public virtual void Write(
string value )
Writes 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
Example 1
Ref: C#Corner Pick “N” Share :C#Zone
21 | P a g e “A room without books is like a body without a soul”
Example 2
Let us see another example that will clarify the concepts.
1. static void Main(string[] args)
2. {
3. string FILE_NAME = "Test_File.data";
4. // Create the new, empty data file.
5. if (File.Exists(FILE_NAME))
6. {
7. Console.WriteLine("{0} is already exists!", FILE_NAME);
8. Console.WriteLine("Please Give Another Name");
9. return;
10. }
11. using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
12. {
13. // Create the writer for data.
14. using (BinaryWriter w = new BinaryWriter(fs))
15. {
16. // Write data to Test.data.
17. for (int i = 0; i < 20; i++)
18. {
19. w.Write(i);
20. }
21. }
22. }
23. // Create the reader for data.
24. using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
25. {
26. using (BinaryReader r = new BinaryReader(fs))
27. {
28. // Read data from Test.data.
29. for (int i = 0; i < 20; i++)
30. {
31. Console.WriteLine(r.ReadInt32());
32. }
33. }
34.
35. Console.ReadKey();
36. }
Output
I hope this article help you learn about File I/O in C#.
Ref: C#Corner Pick “N” Share :C#Zone
22 | P a g e “A room without books is like a body without a soul”
6. Serialization and De-serialization
Serialization
Sometimes, you might want to store a collection of objects to a file and then read them back in
your program. For example, a collection of objects that represents a group of students in a class
have to be stored in a file. These objects will be used later in the program.
Serialization is the process of writing an object to a file. In contrast, deserialization reads the
object back from the file. An object that is serializable must be marked
with Serializable keyword.
In C#, you can use the BinaryFormatter class (in
System.Runtime.Serialization.Formatters.Binary namespace) to write an object to a file and read
the object from the file. To write the object to the file, you will use its Serialize method. The
Serialize method takes two arguments. One argument is the stream object representing the file
that the object will be stored and another argument is the object. Its Deserialize method will
read the object back from the file. It accepts one argument that is the stream object representing
the file to be read from. In the example below, the Student class is marked with the Serializable
keyword so that it can be serialized. The writeObject method can be called to write a student
object to a file. The readObject method will read the object back.
[Serializable()]
class Student
{
private string id;
private string name;
public Student(string id, string name)
{
this.id = id;
this.name = name;
}
public string pid
{
get { return id;}
set { id=value;}
}
public string pname
{
get { return name; }
set { name = value; }
}
}
Ref: C#Corner Pick “N” Share :C#Zone
23 | P a g e “A room without books is like a body without a soul”
static void writeObject(string path)
{
FileStream fs = null;
ArrayList al = new ArrayList() ;
try
{
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, new Student("999", "Dara"));
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
static void readObject(string path)
{
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
Student st =(Student) bf.Deserialize(fs);
Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname);
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
If you want to store a collection of many objects in a file, you need to package the objects in an
ArrayList. Then write the ArrayList object to the file.
Example:
ArrayList al=new ArrayList();
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
al.Add(new Student("0999", "Dara"));
al.Add(new Student("888", "Yuk"));
Simply, you can read the ArrayList object that contains the student objects as shown below:
ArrayList al = (ArrayList)bf.Deserialize(fs)
Ref: C#Corner Pick “N” Share :C#Zone
24 | P a g e “A room without books is like a body without a soul”
Complete Code-Example
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializationDemo
{
[Serializable()]
class Student
{
private string id;
private string name;
public Student(string id, string name)
{
this.id = id;
this.name = name;
}
public string pid
{
get { return id;}
set { id=value;}
}
public string pname
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void writeObject(string path)
{
FileStream fs = null;
ArrayList al = new ArrayList() ;
try
{
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
//al.Add(new Student("0999", "Dara"));
//al.Add(new Student("888", "Yuk"));
bf.Serialize(fs, new Student("0999", "Dara"));
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
Ref: C#Corner Pick “N” Share :C#Zone
25 | P a g e “A room without books is like a body without a soul”
static void readObject(string path)
{
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
Student st =(Student) bf.Deserialize(fs);
Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname);
//ArrayList al = (ArrayList)bf.Deserialize(fs);
//Student st = (Student)al[0];
//Console.WriteLine(st.pid);
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
static void Main(string[] args)
{
writeObject("d:/students.bin");
readObject("d:/students.bin");
Console.Read();
}
}
}

More Related Content

What's hot

High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To ScalaPhilip Schwarz
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
FP Day 2011 - Turning to the Functional Side (using C# & F#)
FP Day 2011 - Turning to the Functional Side (using C# & F#)FP Day 2011 - Turning to the Functional Side (using C# & F#)
FP Day 2011 - Turning to the Functional Side (using C# & F#)Phillip Trelford
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
 

What's hot (18)

High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Strings
StringsStrings
Strings
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
 
Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
FP Day 2011 - Turning to the Functional Side (using C# & F#)
FP Day 2011 - Turning to the Functional Side (using C# & F#)FP Day 2011 - Turning to the Functional Side (using C# & F#)
FP Day 2011 - Turning to the Functional Side (using C# & F#)
 
String Handling
String HandlingString Handling
String Handling
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 

Similar to Week 9 IUB c#

Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
Basic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdfBasic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdfShubhamMadaan9
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxoreo10
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3C# Learning Classes
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingHock Leng PUAH
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2Abbas Ajmal
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 

Similar to Week 9 IUB c# (20)

Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
Oop
OopOop
Oop
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
 
Basic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdfBasic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdf
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docx
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
 
Linked list
Linked listLinked list
Linked list
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
OOPS
OOPSOOPS
OOPS
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Ch2
Ch2Ch2
Ch2
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 

More from Umar Farooq

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-IUmar Farooq
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#Umar Farooq
 
Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Umar Farooq
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#Umar Farooq
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
 
Software process model
Software process modelSoftware process model
Software process modelUmar Farooq
 

More from Umar Farooq (10)

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-I
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Selection Sort
Selection Sort Selection Sort
Selection Sort
 
Matrix
MatrixMatrix
Matrix
 
Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
Software process model
Software process modelSoftware process model
Software process model
 

Recently uploaded

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Week 9 IUB c#

  • 1. C#Zone Week 9(according to IUB outline):- --------------------------------------------------------------------------------- 9. Building .NET-based Applications with C# 1. Examining Microsoft .NET Framework class library 2. The Object Browser 3. Overriding Methods from System.Object class 4. Formatting Strings, Numbers, Currency and date values. 5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream 6. Serialization and De-serialization. --------------------------------------------------------------------------------- Any issue:umarfarooqworld@outlook.com >>Welcome Back<<
  • 2. Ref: C#Corner Pick “N” Share :C#Zone 2 | P a g e “A room without books is like a body without a soul” 1. Examining Microsoft .NET Framework class library The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built. The namespaces and namespace categories in the class library are listed in the following table and documented in detail in this reference. The namespaces and categories are listed by usage, with the most frequently used namespaces appearing first. There are Thousands of .NET Framework class libraries and some is mentioned below: Namespaces Namespace Description System The System namespace contains fundamental classes and base classes that define commonly- used Value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. System.Collections The System.Collections namespaces contain types that define various standard, specialized, and generic collection objects. 2. Using the Object Browser Visual C# 2008 includes a useful tool that enables you to easily view members (properties, methods, and events) of all the objects in a project: the Object Browser (see Figure 3.10). This is useful when dealing with objects that aren’t well documented because it enables you to see all the members an object supports. To view the Object Browser, choose View, Other Windows, Object Browser from the menu.
  • 3. Ref: C#Corner Pick “N” Share :C#Zone 3 | P a g e “A room without books is like a body without a soul” Figure 3.10. The Object Browser enables you to view all properties and methods of an object. The Browse drop-down list in the upper-left corner of the Object Browser is used to determine the browsing scope. You can choose My Solution to view only the objects referenced in the active solution, or you can choose All Components to view all possible objects. You can customize the object set by clicking the drop-down arrow next to the Object Browser Settings button to the far right of the Browse drop-down list. I don’t recommend changing the custom object setting until you have some experience using Visual C# objects as well as experience using the Object Browser. The top-level nodes (each item in the tree is referred to as a node) in the Objects tree are libraries. Libraries are usually DLL or EXE files on your computer that contain one or more objects. To view the objects within a library, simply expand the library node. As you select objects within a library, the list to the right of the Objects tree shows information regarding the members of the selected object (refer to Figure 3.10). For even more detailed information, click a member in the list on the right, and the Object Browser shows information about the member in the area below the two lists.
  • 4. Ref: C#Corner Pick “N” Share :C#Zone 4 | P a g e “A room without books is like a body without a soul” 3. Overriding Methods from System.Object class Introduction: Let us start by creating a new class and we will leave it with out any methods. public class Employee { } In the next step we will try to use our class, we will find that our Employee class contains 4 methods which are (Equals, GetHashCode, GetType, and ToString). The question now, from where these four methods come from? The answer is easy: any data type in the .Net inherits implicitly from the Object class which defines a common set of members supported by every type in the .NET, so when we create our new class Employee it inherits from the Object class. The Object base class defines some members that are virtual so it allows us to redefine the default implementation of these members. These virtual members give you a good work, but in some cases you will need a new implementation of these methods to fit your class functionality. In the next section we will see how to use the default implementation of the Object class virtual methods and then we will try to redefine it by using override keyword to give it a new behavior.
  • 5. Ref: C#Corner Pick “N” Share :C#Zone 5 | P a g e “A room without books is like a body without a soul” ToString() Method: The ToString() method gives you a textual representation of the current state of the object. Example: namespace UsingObjectClass { public class Employee { string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } string lastName; public string LastName { get { return lastName; } set { lastName = value; } } int age; public int Age { get { return age; } set { age = value; } } string employeeID; public string EmployeeID { get { return employeeID; } set { employeeID = value; } } } class Program { static void Main(string[] args) { Employee emp1 = new Employee(); emp1.FirstName = "Amr"; emp1.LastName = "Ashush"; emp1.Age = 23; string s = emp1.ToString(); Console.WriteLine(s); } } }
  • 6. Ref: C#Corner Pick “N” Share :C#Zone 6 | P a g e “A room without books is like a body without a soul” The result: As you can see the returned string is the name of the Employee Type (UsingObjectClass.Employee). What if we want to use the ToString() method to show the current employee data (First Name, Last Name, and Age). All we need to do is to override the ToString() Method to give it a new behavior, so in our case we will redefine it to show the Employee data instead of the name of the object type. Overriding ToString() Method: The first step is to use the override keyword to override the method and then we will redefine its behavior. Example: public class Employee { .... //Overriding ToString() method public override string ToString() { string s = "First Name: " + firstName + " , " + " last Name: " + lastName + " , " +"and Age: " + age; return s; } } Trying the new behavior of the ToString() method: Employee emp1 = new Employee(); emp1.FirstName = "Amr"; emp1.LastName = "Ashush"; emp1.Age = 23; string s = emp1.ToString(); Console.WriteLine(s);
  • 7. Ref: C#Corner Pick “N” Share :C#Zone 7 | P a g e “A room without books is like a body without a soul” The result: As you can see we now have a good text representation of our object. We can use also StringBuilder in our ToString() method as follow: public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("First Name: {0}, Last Name: {1}, and Age: {2}", firstName, lastName, age); return sb.ToString(); } Equals() Method: Equals() method is used to compare two objects and it returns a true if these objects point to the same values on the heap and returns false if not. Example: Employee emp1 = new Employee(); emp1.FirstName = "Amr"; emp1.LastName = "Ashush"; emp1.Age = 23; Employee emp2 = emp1; We now have two objects that point to the same value on the heap, so if we tried to use Equals() method it will return true. //this will return True. emp1.Equals(emp2); Now we will create two objects each one has its own value on the heap, so when we use Equals() method it will return False. Employee emp3 = new Employee(); emp3.FirstName = "Amr"; emp3.LastName = "Ashush"; emp3.Age = 40; emp3.EmployeeID = "123A";
  • 8. Ref: C#Corner Pick “N” Share :C#Zone 8 | P a g e “A room without books is like a body without a soul” Employee emp4 = new Employee(); emp4.FirstName = "Amr"; emp4.LastName = "Ashush"; emp4.Age = 23; emp4.EmployeeID = "123A"; //this will return False. emp3.Equals(emp4); Overriding Equals() Method: Consider that we want to compare two objects but we do not want to know if these objects pointing to the same value in the heap, all we need to know that if these two objects have the same data like (First Name, and Last Name) for example. Example: //Overriding Equals() method public override bool Equals(object obj) { if (obj != null && obj is Employee) { Employee emp = (Employee)obj; if (emp.firstName == this.firstName && emp.lastName == this.lastName && emp.employeeID == this.employeeID) return true; } return false; } Now when we try to use the Equals() method it will compare the firstName, lastName, and employeeID of the two objects and it will return true if these value are the same and false if not. Example: Employee emp1 = new Employee(); emp1.FirstName = "Amr"; emp1.LastName = "Ashush"; emp1.Age = 23; emp1.EmployeeID = "123A"; Employee emp2 = new Employee(); emp2.FirstName = "Amr"; emp2.LastName = "Ashush"; emp2.Age = 23; emp2.EmployeeID = "123A"; //this will return True. emp1.Equals(emp2); If we have two objects with different data Equals method will return false. Employee emp3 = new Employee(); emp3.FirstName = "Jack"; emp3.LastName = "Baher"; emp3.Age = 40; emp3.EmployeeID = "1254B";
  • 9. Ref: C#Corner Pick “N” Share :C#Zone 9 | P a g e “A room without books is like a body without a soul” Employee emp4 = new Employee(); emp4.FirstName = "James"; emp4.LastName = "Bond"; emp4.Age = 23; emp4.EmployeeID = "007"; //this will return False. emp3.Equals(emp4); GetHashCode() Method: The GetHashCode() method is used to return a numerical value that identefies an object based on its internal data. Example: Employee emp1 = new Employee(); emp1.FirstName = "Numan"; emp1.LastName = "Ashraf"; emp1.Age = 23; emp1.EmployeeID = "125"; Employee emp2 = new Employee(); emp2.FirstName = "Ali"; emp2.LastName = "Hashmi"; emp2.Age = 23; emp2.EmployeeID = "125"; Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode()); Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode()); the result will be: emp 1 hash code: 45653674 emp 2 hash code: 41149443 As you can see, instead of the two objects have the same data, each one have different hash code because each object points to a different place on the heap. So if we create two objects that point to the same value, when we call GetHashCode() method from any one we will get the same hash code. Example: Employee emp1 = new Employee(); emp1.FirstName = "Numan"; emp1.LastName = "Ashraf"; emp1.Age = 23; emp1.EmployeeID = "125"; Employee emp2 = emp1; Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode()); Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode()); the result will be: emp 1 hash code: 45653674 emp 2 hash code: 45653674
  • 10. Ref: C#Corner Pick “N” Share :C#Zone 10 | P a g e “A room without books is like a body without a soul” Overriding GetHashCode() Method: We need to override GetHashCode() method so if we have two objects with identical data we will obtain the same hash code. The String class has its own implementation of GetHashCode() method based on the string's character data. We can use the string that return from the overriden ToString() method and use it to call GetHashCode() method. So if we have two objects with the same First Name, Last Name, and Age we will obtain the same hash code. //Overriding the GetHashCode method public override int GetHashCode() { return ToString().GetHashCode(); } Example: Employee emp1 = new Employee(); emp1.FirstName = "Numan"; emp1.LastName = "Ashraf"; emp1.Age = 23; emp1.EmployeeID = "125"; Employee emp2 = new Employee(); emp2.FirstName = "Numan"; emp2.LastName = "Ashraf"; emp2.Age = 23; emp2.EmployeeID = "125"; Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode()); Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode()); the result will be:(the same hash code) emp 1 hash code: -1503318716 emp 2 hash code: -1503318716 As you can see we get the same hash code although we have two object that are point to different values on the heap. Another option is to identify a string field that should be unique among objects and then return its hash code. In our case EmployeeID suould be unique so if we have two object with the same EmployeeID we will get the same hash code. //Overriding the GetHashCode method public override int GetHashCode() { return EmployeeID.GetHashCode(); } Note: Overriding GetHashCode() method only useful when you want to store your object in hash- based collection such as Hashtable beacause the Hashtable type calles the Equals() and GetHashCode() methods of the contained objects under the hood to determine the correct object to return to the caller. and the Object class has no idea about the data on its subclasses.
  • 11. Ref: C#Corner Pick “N” Share :C#Zone 11 | P a g e “A room without books is like a body without a soul” 4. Formatting Strings, Numbers, Currency and date values. The Syntax of the String.Format() Method The general syntax of the String.Format() method is as follows: String.Format("format string", arg1, arg2, .... ); The format string is the string into which the values will be placed. Within this string are place holders which indicate the location of each value within the string. Place holders take the form of braces surrounding a number indicating the corresponding argument to be substituted for the place holder. Following on from the format string is a comma separated list of arguments. There must be an argument for each of the place holders. A Simple C# String Format Example The following code fragment demonstrates a very simple use of the String.Format() method: string newString; newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs"); System.Console.WriteLine (newString); When run, the above code will result in the following output: There are 2 cats in my house and no dogs Let's quickly review the String.Format() method call. The format string contains 3 place holders indicated by {0}, {1} and {2}. Following the format string are the arguments to be used in each place holder. For example, {0} is replaced by the first argument (the number 2), the {1} by the second argument (the string "house") and so on.
  • 12. Ref: C#Corner Pick “N” Share :C#Zone 12 | P a g e “A room without books is like a body without a soul” Formatting Dates and Times in C# There are number of techniques available for extracting and displaying dates and times in particular formats. Output may be configured using a small number of predefined formatting methods or customized with an almost infinite number of variations using the ToString() method. The basic formatting methods operate as follows: DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0); System.Console.WriteLine(meetingAppt.ToLongDateString()); // Monday, September 22, 2008 System.Console.WriteLine(meetingAppt.ToShortDateString()); // 9/22/2008 System.Console.WriteLine(meetingAppt.ToShortTimeString()); // 2:30 PM If the above prepackaged formatting methods do not provide the required output, a formidable variety of custom formats may be constructing using the ToString() method. The ToString() method takes as an argument a format string which specifies precisely how the date and time is to be displayed. The following example shows a few of this formats in action. The subsequent table lists all the possible format variables which may be used: DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0); System.Console.WriteLine(meetingAppt.ToString("MM/dd/yy")); // 09/22/08 System.Console.WriteLine(meetingAppt.ToString("MM - dd - yyyy")); // 09 - 22 - 2008 System.Console.WriteLine(meetingAppt.ToString("ddd dd MMM yyyy")); // Mon 22 Sep 2008 System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // Monday September 22 2008 The full list of format patterns support by the ToString() method of the C# DateTime class is as follows: Format Specifier Description d The day of the month. Single-digit days will not have a leading zero. dd The day of the month. Single-digit days will have a leading zero. ddd The abbreviated name of the day of the week, as defined in AbbreviatedDayNames. dddd The full name of the day of the week, as defined in DayNames. M The numeric month. Single-digit months will not have a leading zero. MM The numeric month. Single-digit months will have a leading zero. MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames. MMMM The full name of the month, as defined in MonthNames.
  • 13. Ref: C#Corner Pick “N” Share :C#Zone 13 | P a g e “A room without books is like a body without a soul” Currency In this article we will learn how to display a number in its currency format with respect to a country. When we want to display a number in its respective country's currency format, we format the string in the currency format and get the currency symbol of a specific country using the "CultureInfo" class available in .Net. To use the CultureInfo class, we need to include the "System.Globalization" Namespace in our program. The "C" format specifier converts a number to a string that represents a currency amount. The precision specifier indicates the desired number of decimal places in the result string. If the precision specifier is omitted then the default precision is used (the default value is 2). If the value to be formatted has more than the specified or the default number of decimal places then the fractional value is rounded in the result string. If the value to the right of the number of the specified decimal places is 5 or greater then the last digit in the result string is rounded away from zero. Here is code showing how to convert a number to its corresponding currency format for a respective country: using System; using System.Globalization; namespace CurrencyFormatter { class Program { static void Main(string[] args) { double value = 5623345.6789; //For Current Culture Console.WriteLine("n--------- Displaying Currency in Current Culture ---------------n"); // By default, single letter C displays currency upto two decimal digits Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture)); // C2 displays currency upto two digits Console.WriteLine(value.ToString("C2", CultureInfo.CurrentCulture)); // C3 displays currency upto three digits Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture)); // C4 displays currency upto four digits Console.WriteLine(value.ToString("C4", CultureInfo.CurrentCulture)); // C5 displays currency upto five digits Console.WriteLine(value.ToString("C5", CultureInfo.CurrentCulture));
  • 14. Ref: C#Corner Pick “N” Share :C#Zone 14 | P a g e “A room without books is like a body without a soul” //For Japan Console.WriteLine("n--------- Dispalying Currency for Japan ---------------n"); Console.WriteLine(value.ToString("C", CultureInfo.CreateSpecificCulture("ja-JP"))); //For Denmark Console.WriteLine("n--------- Dispalying Currency for Denmark ---------------n"); Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("da-DK"))); //For India Console.WriteLine("n--------- Dispalying Currency for India ---------------n"); Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("en-IN"))); Console.Read(); } } }
  • 15. Ref: C#Corner Pick “N” Share :C#Zone 15 | P a g e “A room without books is like a body without a soul” Numbers Number of time the end user / client require to display numeric data in different format. In this post I am going to discuss about the various type of the custom format that provided by C#.net to achieve requirement. Here I am going to discuss each format one by one.. "0" Custom Specifier ToString("00000") - format put the leading 0 when number get display if digits in number less than the number of zero specified. when the below code is get executed output display 01234 because the number of digit less than the number of zero. double value; value = 1234; Console.WriteLine("Format 1: " + value.ToString("00000")); Console.WriteLine(); ToString("00.00") - format do same thing as above replace zero if the number digit less , but the zero after decimal point allows to display digit equals number of zero after decimal if the number of digit less than display zero in place of that. output of the following code is 01.24 i.e only 2 digit allowed after decimal point. Note : - decimal point is display as per specified culture. value = 1.235; Console.WriteLine("Format 2: " + value.ToString("00.00",CultureInfo.InvariantCulture)); Console.WriteLine(); ToString("0,0") - format cause to display comma between number. here when the following code is get executed , is get display after every three digit 1,234,567,890. Note : - in this comma get replace by the culture. value = 1234567890; Console.WriteLine("Format 3: " + value.ToString("0,0",CultureInfo.InvariantCulture)); Console.WriteLine(); ToString("0,0.0") - format is combination of above format. value = 1234567890.123456; Console.WriteLine("Format 4: " + value.ToString("0,0.0",CultureInfo.InvariantCulture)); Console.WriteLine(); Output
  • 16. Ref: C#Corner Pick “N” Share :C#Zone 16 | P a g e “A room without books is like a body without a soul” 5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream Introduction In memory, objects cease to exist when a program ends. But files exist until deletion. With files we persist data. A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically a sequence of bytes passing through the communication path. There are two main streams, the input stream and the output stream. The input stream is used for reading data from a file (read operation) and the output stream is used for writing into the file (write operation). We handle them with types in System.IO. Various Types of C# I/O Classes The System.IO namespace has various classes for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file and so on. Some important classes are as follows: I/O Class Description FileStream Used to read from and write to any location in a file BinaryReader Reads primitive data from a binary stream BinaryWriter Writes primitive data in binary format File Use for manipulating files StreamReader Used for reading characters from a byte stream StreamWriter Is used for writing characters to a stream StringReader Is used for reading from a string buffer StringWriter Is used for writing into a string buffer Directory Helps in manipulating a directory structure DirectoryInfo Used for performing operations on directories Now we see examples of some important I/O class and examine the outputs. The FileStream Class The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows: 1. FileStream <object_name> = new FileStream( <file_name>,<FileMode Enumerator>, <FileAccess Enumerat or>, <FileShare Enumerator>); For example, create a FileStream object F for reading a file named Example.txt as: 1. FileStream My_File = new FileStream("Example.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare .ReadWrite);
  • 17. Ref: C#Corner Pick “N” Share :C#Zone 17 | P a g e “A room without books is like a body without a soul” Now we see the meaning of each parameter. FileMode The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are: Mode Description Append It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist Create It creates a new file. If file is already exist then it will overrite that file CreateNew It will also use to create a new file If the file is already exist then it will throw an Exception Open It opens an existing file OpenOrCreate It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file Truncate It opens an existing file and truncates its size to zero bytes FileAccess The FileAccess enumerator defines the kind of task to do with the file. AccessMode Description Read Data can be write from file Write Data can be write written to the file ReadWrite Data can be written to and read from the file FileShare This enumerator applies the type of permission for sharing. SharingMode Description Inheritable It allows a file handle to pass inheritance to the child processes None It declines sharing of the current file Read It allows opening the file for reading ReadWrite It allows opening the file for reading and writing Write It allows opening the file for writing Example The following program shows the use of the FileStream class:
  • 18. Ref: C#Corner Pick “N” Share :C#Zone 18 | P a g e “A room without books is like a body without a soul” Stream Reader and Stream Writer The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream that supports reading and writing bytes into a file stream. The StreamReader Class The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class: Method Name Description public override void Close() It closes the StreamReader object and the underlying stream and releases any system resources associated with the reader. public override int Peek() Returns the next available character but does not consume it public override int Read() Reads the next character from the input stream and advances the character position by one character The StreamWriter Class The StreamWriter class inherits from the abstract class TextWriter that represents a writer that can write a series of characters. The following table shows some of the most commonly used methods of this class: Method Description public override void Close() Closes the current StreamWriter object and the underlying stream public override void Flush() Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream public virtual void Write(bool value) Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.) public override void Write( char value ) Writes a character to the stream public virtual void Write( decimal value ) Writes the text representation of a decimal value to the text string or stream public virtual void Write( double value ) Writes the text representation of an 8-byte floating-point value to the text string or stream public virtual void Write( int value ) Writes the text representation of a 4-byte signed integer to the text string or stream public override void Write( string value ) Writes a string to the stream public virtual void WriteLine() Writes a line terminator to the text string or stream
  • 19. Ref: C#Corner Pick “N” Share :C#Zone 19 | P a g e “A room without books is like a body without a soul” Example The following example shows writing text data into a file using the StreamWriter class: Binary Reader and Binary Writer The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file. The BinaryReader Class The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor. The following table shows some of the commonly used methods of the BinaryReader class: Method Description public override void Close() It closes the BinaryReader object and the underlying stream public virtual int Read() Reads the characters from the underlying stream and advances the current position of the stream public virtual bool ReadBoolean() Reads a Boolean value from the current stream and advances the current position of the stream by one byte public virtual char 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 public virtual char[] ReadChars( int count ) Reads the specified number of 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 public virtual string 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. Ref: C#Corner Pick “N” Share :C#Zone 20 | P a g e “A room without books is like a body without a soul” The BinaryWriter Class The BinaryWriter class writes binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor. The following table shows some of the commonly used methods of the BinaryWriter class: Method Description public override void Close() It closes the BinaryWriter object and the underlying stream public virtual long Seek( int offset, SeekOrigin origin ) Sets the position within the current stream public virtual void Write( byte[] buffer ) Writes a byte array to the underlying stream public virtual void Write( char ch ) Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream public virtual void Write( char[] chars ) Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream public virtual void Write( string value ) Writes 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 Example 1
  • 21. Ref: C#Corner Pick “N” Share :C#Zone 21 | P a g e “A room without books is like a body without a soul” Example 2 Let us see another example that will clarify the concepts. 1. static void Main(string[] args) 2. { 3. string FILE_NAME = "Test_File.data"; 4. // Create the new, empty data file. 5. if (File.Exists(FILE_NAME)) 6. { 7. Console.WriteLine("{0} is already exists!", FILE_NAME); 8. Console.WriteLine("Please Give Another Name"); 9. return; 10. } 11. using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew)) 12. { 13. // Create the writer for data. 14. using (BinaryWriter w = new BinaryWriter(fs)) 15. { 16. // Write data to Test.data. 17. for (int i = 0; i < 20; i++) 18. { 19. w.Write(i); 20. } 21. } 22. } 23. // Create the reader for data. 24. using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)) 25. { 26. using (BinaryReader r = new BinaryReader(fs)) 27. { 28. // Read data from Test.data. 29. for (int i = 0; i < 20; i++) 30. { 31. Console.WriteLine(r.ReadInt32()); 32. } 33. } 34. 35. Console.ReadKey(); 36. } Output I hope this article help you learn about File I/O in C#.
  • 22. Ref: C#Corner Pick “N” Share :C#Zone 22 | P a g e “A room without books is like a body without a soul” 6. Serialization and De-serialization Serialization Sometimes, you might want to store a collection of objects to a file and then read them back in your program. For example, a collection of objects that represents a group of students in a class have to be stored in a file. These objects will be used later in the program. Serialization is the process of writing an object to a file. In contrast, deserialization reads the object back from the file. An object that is serializable must be marked with Serializable keyword. In C#, you can use the BinaryFormatter class (in System.Runtime.Serialization.Formatters.Binary namespace) to write an object to a file and read the object from the file. To write the object to the file, you will use its Serialize method. The Serialize method takes two arguments. One argument is the stream object representing the file that the object will be stored and another argument is the object. Its Deserialize method will read the object back from the file. It accepts one argument that is the stream object representing the file to be read from. In the example below, the Student class is marked with the Serializable keyword so that it can be serialized. The writeObject method can be called to write a student object to a file. The readObject method will read the object back. [Serializable()] class Student { private string id; private string name; public Student(string id, string name) { this.id = id; this.name = name; } public string pid { get { return id;} set { id=value;} } public string pname { get { return name; } set { name = value; } } }
  • 23. Ref: C#Corner Pick “N” Share :C#Zone 23 | P a g e “A room without books is like a body without a soul” static void writeObject(string path) { FileStream fs = null; ArrayList al = new ArrayList() ; try { fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, new Student("999", "Dara")); } catch (Exception e) { Console.WriteLine(e.Message); } finally { fs.Close(); } } static void readObject(string path) { FileStream fs = null; try { fs = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryFormatter bf = new BinaryFormatter(); Student st =(Student) bf.Deserialize(fs); Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname); } catch (Exception e) { Console.WriteLine(e.Message); } finally { fs.Close(); } } If you want to store a collection of many objects in a file, you need to package the objects in an ArrayList. Then write the ArrayList object to the file. Example: ArrayList al=new ArrayList(); fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryFormatter bf = new BinaryFormatter(); al.Add(new Student("0999", "Dara")); al.Add(new Student("888", "Yuk")); Simply, you can read the ArrayList object that contains the student objects as shown below: ArrayList al = (ArrayList)bf.Deserialize(fs)
  • 24. Ref: C#Corner Pick “N” Share :C#Zone 24 | P a g e “A room without books is like a body without a soul” Complete Code-Example using System; using System.Collections; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace SerializationDemo { [Serializable()] class Student { private string id; private string name; public Student(string id, string name) { this.id = id; this.name = name; } public string pid { get { return id;} set { id=value;} } public string pname { get { return name; } set { name = value; } } } class Program { static void writeObject(string path) { FileStream fs = null; ArrayList al = new ArrayList() ; try { fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryFormatter bf = new BinaryFormatter(); //al.Add(new Student("0999", "Dara")); //al.Add(new Student("888", "Yuk")); bf.Serialize(fs, new Student("0999", "Dara")); } catch (Exception e) { Console.WriteLine(e.Message); } finally { fs.Close(); } }
  • 25. Ref: C#Corner Pick “N” Share :C#Zone 25 | P a g e “A room without books is like a body without a soul” static void readObject(string path) { FileStream fs = null; try { fs = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryFormatter bf = new BinaryFormatter(); Student st =(Student) bf.Deserialize(fs); Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname); //ArrayList al = (ArrayList)bf.Deserialize(fs); //Student st = (Student)al[0]; //Console.WriteLine(st.pid); } catch (Exception e) { Console.WriteLine(e.Message); } finally { fs.Close(); } } static void Main(string[] args) { writeObject("d:/students.bin"); readObject("d:/students.bin"); Console.Read(); } } }