Printable Version
I/O in C# Unleased
By K.Vineel Kumar Reddy
Object
|
\----BinaryReader------\
| |-->Binary IO used to read primitive data types(int,char..)
|----BinaryWriter------/
|
|
|----Stream(Abstract) ---> Byte Oriented IO
| |
| \
| |-----FileStream
| |-----BufferedStream
| `-----MemoryStream
|
|
|----TextReader(Abstract) ---> Character Based IO (For Reading....)
| |
| \
| |-----StreamReader
| `-----StringReader
|
`----TextWriter(Abstract) ---> Character Based IO (For Writing....)
|
\
|-----StreamWriter
`-----StringWriter
The Classes that are presented here are all from System.IO namespace.So make sure
you include it before doing IO programs.
#################################################################
To Reading Character data (ex:- reading Text Files....)
1.Use StreamReader with File path as string in the constructor.
2.Use ReadLine() Method to read each line in the given file.
3.repeat step 2 until ReadLine() Method return null indicating end of File.
4.Close the StreamReader at Last.
To Writing Character data (ex:- writing Text Files....)
1.Use StreamWriter with File path as string in the constructor.
2.Use WriteLine("....") Method to write each line to the given file.
3.repeat step 2 until there is no data to write.
4.Close the StreamWriter at Last.
example:-
---------
class IOStreams
{
static void Main()
{
//Writing
StreamWriter sw = new StreamWriter(@"d:\a.txt");
sw.WriteLine("Hai I am Vineel...");
sw.WriteLine("This is from C#");
sw.Close();
//Reading
StreamReader sr = new StreamReader(@"d:\a.txt");
Console.WriteLine(sr.ReadLine());
Console.WriteLine(sr.ReadLine());
sr.Close();
}
}
##############################################################
To Read Chunks of bytes from a file (ex:- reading few bytes from an exe file...)
1.Use FileStream with first parameter to contructor as File path(as string)
and FileMode (Open,Create,Append,Truncate...) as second parameter.
2.Create an array of bytes with some size (say 1024 ...)
3.Pass this array to Read Method as fs.Read(byte[],offset,count); where
byte[] indicates byte array created, offset indicates from where the array
should be started filling(in most cases it is Zero) and count indicates
number bytes to be copied.In this case it is 1024(it can be any thing
otherthan 1024);
4.When above read Method is executed you will have byte array filled with the requried
data.If nothing is read in to array Read method returns zero(with which we can
conclude that we have reached end of file..).The return value always indicates
number of byte read in to the array.(This is not always equal to count value we have
passed .For more clarity read last section in this tutorial....)
5.If you want read once again repeat step 3
6.Close the FileStream at Last
**************THIS IS EXACTLY SIMILAR TO read SYSTEM CALL IN LINUX****************
To Write Chunks of bytes to a file (ex:- Writing few bytes to an exe file...)
1.Use FileStream with first parameter to contructor as File path(as string)
and FileMode (Open,Create,Append,Truncate...) as second parameter.
2.Create an array of bytes with some size (say 1024 ...) and fill it with some bytes.
3.Pass this array to Write Method as fs.Write(byte[],offset,count); where
byte[] indicates byte array created, offset indicates from which offset of the array
the bytes should be copied(in most cases it is Zero) and count indicates
number bytes to be copied.In this case it is 1024(it can be any thing
otherthan 1024);
4.When above write Method is executed you will have byte array copied to the requried
file.If nothing is wrote from the array Write method returns zero(with which we can
conclude that there is no data in the byte array..).The return value always indicates
number of byte wrote from the array.(This is not always equal to count value we have
passed .For more clarity read last section in this tutorial....)
5.If you want write once again repeat step 3
6.Close the FileStream at Last
**************THIS IS EXACTLY SIMILAR TO write SYSTEM CALL IN LINUX****************
example:-
---------
class IOStreams
{
static void Main()
{
FileStream fs = new FileStream(@"d:\xyz.exe", FileMode.OpenOrCreate);
int Size = 1024;
byte []data = new byte[Size];
int b = fs.Read(data,0,Size);
while(b!=0)
{
b = fs.Read(data,0,Size);
//manipulate data here....
}
fs.Close();
}
}
####################################################################
To Read (or Write) primitive values from (or to) files
(ex:- reading int,char,double... from files)
example:-
---------
//Usage of BinaryReader and BinaryWriter
class IOStreams
{
static void Main()
{
//Writing
Stream sin = new FileStream(@"d:\a.txt", FileMode.Create);
BinaryWriter bw = new BinaryWriter(sin);
bw.Write(124);
bw.Write("Vineel");
bw.Close();
sin.Close();
//Reading
Stream sout = new FileStream(@"d:\a.txt", FileMode.Open);
BinaryReader br = new BinaryReader(sout);
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadString());
br.Close();
sout.Close();
}
}
Open the created text file in Notepad and see.You will find only cryptic characters
not the values inserted.But what is amazing is the data wrote to the file is exactly
read back by BinaryReader even though we cannot recognise it manually.
##########################################################################
CHOOSING WHICH CLASSES TO USE WHEN
----------------------------------
1.Most probably when you want to manipulate a text file for example copying it or reading
from it go for StreamReader and StreamWriter
2.When you want to manipulate byte files like MP3,EXE files for example extracting bitrate
from an MP3 file or even copying to MP3 Files go for FileStream.
3.Finally storing data in predefined sequence and also to retriving it in that sequence
for example student details like RollNumber(int),Name(String), FeePaid(double) .e.t.c
go for BinaryReader and BinaryWriter because they make reading process easier without
we worrying about how the data is stored in the file.In this case we can simply call
br.ReadInt32() for RollNumber,br.ReadString() for Name,br.ReadDouble() for FeePaid to
get the data stored.
##########################################################################
return values from Read or Write methods need not always equal to their count parameter
----------------------------------------------------------------------------------------
Consider a file having 25 bytes and if we are reading(writing) it in a bulk of 10 bytes
(means count=10) we need to call Read (or Write) method 3 times.In first two Read(or Write)
calls the value returned is equal to count value . But now when these two Read (or Write)
calls completed we have only 5 more bytes to read (or write) so at this point
even though the Read (or Write) method is supposed to read (Or write) 10 bytes it will
only read (Or write) 5 bytes and accordingly the return value is only 5 in this case ....
-----------------------------------------------------------------------------------------
There are many more classes in .NET Framework concerned with IO.Only basic classes
are dealt here.
|