FILE READING AND WRITING?
Reading from and Writing to Text Files.
FILESTREAM CLASS:
FileStream class used to read and write operating system files. FileStream can be used to perform the basic operations of reading and writing operating system files.
What is Encoding?
convert (information or an instruction) into a particular form.
PROGRAM:(fileStreamEg.cs)
using System;
using System.IO;
using System.Text;
namespace fileStreamEg
{
class Program
{
static void Main(string []args)
{
try
{
FileStream fs=new FileStream(@"D:\sample.txt",FileMode.Create,FileAccess.ReadWrite);
byte[] b=Encoding.ASCII.GetBytes("Hello World");//encoding the string and store in a byte array
for(int i=0;i<b.Length;i++)
{
fs.WriteByte(b[i]); //Write a data in to the file
}
Console.WriteLine("Current Position:"+fs.Position.ToString());
fs.Seek(0,SeekOrigin.Begin);
int data;
while((data=fs.ReadByte())>-1) // read bytes until read all
{
Console.WriteLine((char)data);
}
fs.Close();
Console.WriteLine("File is created");//for user identification
}
catch(Exception e){Console.Write(e.Message);}
}
}
}
OUTPUT:
CONSOLE WINDOW OUTPUT:
D:\csharp>fileStreamEg
Current Position:11
H
e
l
l
o
W
o
r
l
d
File is created
FILE:(sample.txt)
Hello World
PROGRAM EXPLANATION:
The above program explain the read and write the file using filestream class,the file stream class used to perform the basic operation in files, Encoding.ASCII.GetBytes() that function encoding a given text to encoding format,and then the data write on a file and then read.