You are on page 1of 7

File Handling

Until now, we had come across different ways to store the data in bulk by using
collections, arrays etc., but all the data is stored in the primary memory whose
disadvantage is we cannot access the same data when the program is terminated. But in
case if we want to store the data permanently so that we can see that data next time,
the only option is Files.

Let us say for example, you have developed an application and while submitting it to the
client, you want to explain him about some sort of exception messages that may come
across while running application. In this case you can make use of files to tell the client
about the exception that is coming exactly and also any other description or information
that you want to give to the client like to understand at what time and in how much
frequencies and which errors are coming.

Dealing with files that is creating a file, opening a file, reading file, writing to file, moving
a file, deleting a file so on and so forth is nothing but file handling.

Before moving on to the exact file handling concept, we should know what are Files and
what is Stream.

Files:
Files allows us to store data in permanent storage or retrieve from it either in text
format or in binary format. These files and the data in it can be handled
programmatically which is nothing but file handling.

Let us see different mode of file used in real time environment..

Create
New file will be created in this mode and if the file is already exists, it will be overridden.
Append
In this mode, if the file exists then the contents will be added at the end of the file. But if
file doesn’t exists, new file will be created.
Create New
This will create a new file and if exists already, it will throw exception.
Open
In this mode existing file will be opened and if the file doesn’t exists, it will throw
exception.
OpenRead
In this mode existing file is opened for reading the contents
.Truncate
In this mode, existing file will be opened and all the contents of the file will be removed.
But if the file doesn’t exists, it will throw exception.

Some of the methods which the File class is providing are as follows:

AppendText(string)

This method creates StreamWriter to append text in the specified file if the file exists,
else it writes in a new file

Copy(string, string)
This method copies an existing file to a new file. It will not allow to copy from one file to
another file with same filename.

Copy(string, string, boolean)


This method copies an existing file to a new file. It will allow to overwrite file of the
same filename.

CreateText(string)
Creates or opens file for writing.

Delete(string)
Deletes the specified file

Exists(string)
It determines whether the file exists or not

Move(string, string)
Moves the file specified in the first argument to a new path mentioned in the second
argument.

OpenRead(string)
Opens the specified file to read if exists

OpenText(string)
Opens an existing text file for reading

OpenRead(string)
Open the specified file to read if exists, if it doesn’t exists creates a new file for writing.

Stream:
In order to handle file operations, the data flowing between source and destination is
divided into small chunks which is nothing but stream.
A stream is nothing but a channel between an input device like keyboard, mouse etc.,
and an output device like file, printer etc.,

Dot Net is providing FileStream, StreamReader, StreamWriter, BInaryReader,


BinaryWriter to read data from file and write data to file.
Stream provides a way to interact with byte sequence.

Let us see some of the common stream member functions:

Functions/Methods Description

Read(), ReadByte() From the current stream, these functions


read sequence of bytes
Seek() To set position in current stream

Write(), WriteByte() These methods write sequence of bytes to


current stream

Position() It gives the current position in the stream

Flush() Underlying data source is updated first with


the current buffer state and then clears the
buffer

Length() It gives the length of the stream in bytes

Close() It closes the current stream and releases all


the associated stream resources if any.

FileStream

FileStream class represents a file. FileStream allows to move data to the stream or from
the stream as array of bytes.
To construct a file stream, we take a file to access, decide the mode of how to open file
and how the file want to be accessed and at last specify share access if any.
FileMode -- Create, Append, Open, CreateNew, Truncate, OpenOrCreate

FileAccess -- Read, Write, ReadWrite

FileShare -- Inheritable, Read, None, Write, ReadWrite

Some of the mostly used classes which the namespace System.IO is providing for file
operations are here..

File class:
This class provides static methods to create, copy, delete, move and open a file and
helps in the creation of FileStream objects.

File Stream:
FileSystem allows us to read/write data to and from a file as array of bytes using stream.
File Info:
This provides properties and instance methods for create, copy delete, move and open
files. It helps in creating FileStream objects. FileInfo cannot be inherited.
Directory Info
This class provides instance methods for creating, moving, enumerate through
directories and sub-directories. This class cannot be inherited.
BinaryReader/BinaryWriter
It supports to read/write primitive datatypes in binary format
StreamReader/StreamWriter
Stream Reader is used to read data from a file by using streams whereas StreamWriter
is helpful in writing data to a file using streams
DriveInfo
This class helps to access information from drives.

Using File Class

Let us see an example to demonstrate the usage of File class..


Here we have taken a windows form
And added a button to it

FH_Fig1

When we double click on the button, .cs file is opened to code the button
Add Systems.IO namespace as shown below and write the code in the button1_click

using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
File.Create(@"E:\data\sample.txt");
// File.Copy(@"E:\data\sample.txt", @"E:\data1\sample.txt");
// File.Move(@"E:\data\sample.txt", @"E:\data1\moved.txt");
// File.Delete(@"E:\data1\moved.txt");

}
}
}

Analysis:
We just created a text file using File.Create()
And copied that file from one path to another path where File.Copy() copies from
source file name to destination file name.
File.Move() moves file from source path to destination path
And File.Delete deletes the file in the given path.

Using StreamReader and StreamWriter

Let us see an example code to demonstrate on StreamReader and StreamWriter

In this code we are about to show you how to write data in the
file and read data from file to the text box.

Take a windows form and drag two buttons and two text boxes as
shown in the figure below.

FH_Fig2
Write the below code in button click events of .cs file

using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(@"E:\data\Myfile.txt");
StreamWriter swriter = file.CreateText();
swriter.WriteLine(textBox1.Text);
swriter.Close();
MessageBox.Show("File is written successfully");
}

private void button2_Click(object sender, EventArgs e)


{
string filename = @"E:\data\Myfile.txt";
StreamReader sreader = File.OpenText(filename);
string str = "";
while ((str = sreader.ReadLine())!= null)
{
textBox2.Text += str;
}
sreader.Close();
}
}
}

Analysis
In button1_Click event,

FileInfo is the class for which we have created an object file and passed the file path as an
argument to it.
Because in order write data from textbox to file, we need a file.
swriter is an object of StreamWriter using which text typed in the textbox1 is written to
the file

In button2_Click event,

sreader, the object of StreamReader will open the file mentioned in the path to read the
contents.
str is a string variable used to store data read from the file where ReadLine() method
helps to read line by line
Until there are contents in the file sreader reads data from file and store it in str.
Text in the Textbox2 is concatenated with the text in str and stored again in textbox2.

You might also like