.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

File Handling

Posted By:Shashi Ray       Posted Date: February 24, 2009    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

File Handling


The file handling objects in C# provide you with some fairly flexible methods of handling files.

The File Object:

The File object represents a file, and has useful methods for testing for a file's existence as well as renaming and deleting a file. All of its methods are static, which means that you do not ( and cannot) create an instance of File using the new operator. Instead, you use its methods directly.


if (File.Exists ("Foo.txt"))

File.Delete ("foo.txt");


You can also use the File object to obtain a FileStream for reading and writing file data:

//open text file for reading

StreamReader ts = File.OpenText ("foo1.txt");

//open any type of file for reading

FileStream fs = File.OpenRead ("foo2.any");


Some of the more useful File methods are shown in the table below:

Static method Meaning

File.FileExists(filename) true if file exists

File.Delete(filename) Delete the file

File.AppendText(String) Append text

File.Copy(fromFile, toFile) Copy a file

File.Move(fromTile, toFile) Move a file, deleting old copy

File.GetExtension(filename) Return file extension

File.HasExtension(filename) true if file has an extension.


Reading Text File

To read a text file, use the File object to obtain a StreamReader object. Then use the text stream's read methods:


StreamReader ts = File.OpenText ("foo1.txt");

String s =ts.ReadLine ();


Writing a Text File

To create and write a text file, use the CreateText method to get a StreamWriter object.


//open for writing

StreamWriter sw = File.CreateText ("foo3.txt");

sw.WriteLine ("Hello file");


If you want to append to an existing file, you can create a StreamWriter object directly with the Boolean argument for append set to true:


//append to text file

StreamWriter asw = new StreamWriter ("foo1.txt", true);


Exceptions in File Handling                  


A large number of the most commonly occurring exceptions occur in handling file input and output. You can get exceptions for illegal filenames, files that do not exist, directories that do not exist, illegal filename arguments and file protection errors. Thus, the best way to handle file input and output is to enclose file manipulation code in Try blocks to assure yourself that all possible error conditions are caught, and thus prevent embarrassing fatal errors. All of the methods of the various file classes show in their documentation which methods they throw. You

can assure yourself that you catch all of them by just catching the general Exception object, but if you need to take different actions for different exceptions, you can test for them separately.

For example, you might open text files in the following manner:


try {

//open text file for reading

StreamReader ts = File.OpenText ("foo1.txt");

String s =ts.ReadLine ();


catch(Exception e ) {

Console.WriteLine (e.Message );



Testing for End of File:


There are two useful ways of making sure that you do not pass the end of a text file: looking for a null exception and looking for the end of a data stream. When you read beyond then end of a text file, no error occurs and no end of file exception is thrown. However, if you read a string after the end of a file, it will return as a null value. You can use this to create an end-of-file function in a file reading class:


private StreamReader rf;

private bool eof;


public String readLine () {

String s = rf.ReadLine ();

if(s == null)

eof = true;

return s;



public bool fEof() {

return eof;



The other way for making sure you don't read past then end of a file is to peek ahead using the Stream's Peek method. This returns the ASCII code for the next character, or a -1 if no characters remain.


public String read_Line() {

String s = ""

if (rf.Peek() > 0) {

s = rf.ReadLine ();




return s;




Shashi Ray

 Subscribe to Articles


Further Readings:

Author: Ramesh         Company URL: http://www.dotnetspark.com
Posted Date: February 25, 2009

Very good sir...easy to understand...


Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend