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


Top 5 Contributors of the Month
david stephan

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

 Subscribe to Articles

A csFile Class

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

A csFile Class

It is sometimes convenient to wrap these file methods in a simpler class with easy to use methods. We have done that here in the csFile class.

 

We'll be using this convenience class in some of the examples in later chapters. We can include the filename and path in the constructor or we can pass it in using the overloaded OpenForRead and OpenForWrite statements.

 

public class csFile

{

private string fileName;

StreamReader ts;

StreamWriter ws;

private bool opened, writeOpened;

//-----------

public csFile() {

init();

}

//-----------

private void init() {

opened = false;

writeOpened = false;

}

//-----------

public csFile(string file_name) {

fileName = file_name;

init();

}

 

We can open a file for reading using either of two methods, once including the filename and one which uses a filename in the argument.

 

public bool OpenForRead(string file_name){

fileName = file_name;

try {

ts = new StreamReader (fileName);

opened=true;

}

catch(FileNotFoundException e) {

return false;

}

return true;

}

//-----------

public bool OpenForRead() {

return OpenForRead(fileName);

}

 

You can then read data from the text file using a readLine method:

 

public string readLine() {

return ts.ReadLine ();

}

Likewise, the following methods allow you to open a file for writing and write lines of text to it.

 

public void writeLine(string s) {

ws.WriteLine (s);

}

//-----------

public bool OpenForWrite() {

return OpenForWrite(fileName);

}

//-----------

public bool OpenForWrite(string file_name) {

try{

ws = new StreamWriter (file_name);

fileName = file_name;

writeOpened = true;

return true;

}

catch(FileNotFoundException e) {

return false;

}

}

 

Shashi Ray


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

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