-->

Wednesday, June 12, 2013

How to create, read, write and delete a text file in windows forms c#

How to create, read, write and delete a text file in windows forms c#

We all know about text files. Text files can contain plain text as well as encrypted text also. A programmer can use these files as a Database in his/her program like to save some Questions to be done by students in their lab, etc.

A programmer don’t know about the hard drives of client’s computer, so we will use our project’s current directory as a path of our files. In Visual Studio, Environment.CurrentDirectory denotes our project’s bin directory.


There are some inbuilt classes which we will use here for our operations like File, FileInfo, StreamWriter, and StreamReader. These all are in System.IO namespace. These classes have thier own methods and properties on which we will work. In this article we will learn how to


  • Create a text file
  • Write data to that file
  • Read data from that File
  • Delete that file

To do some operation with files, create a local variable of type string having path of our project’s current directory with filename:

string path = Environment.CurrentDirectory + "/" + "ab.txt";

Create a text file

if (!File.Exists(path))     //check if file exist or not
    File.Create(path);      //create file if not exist

Here above, first we should have a path to create a file. Then check whether the specified file not exist and then create that file using our last statement i.e. File.Create(path).

Write text to file:

if (File.Exists(path))      //Check if file exist or not
{
    StreamWriter sw = new StreamWriter(path);//create an instance of StreamWriter
    sw.WriteLine("Test Data");               //Write some data in opened file
    sw.Close();                              //close StreamWriter after writing
}

Read text from file:

if (File.Exists(path))      //Check if file exist or not
{
    StreamReader sr = new StreamReader(path);//create an instance of StreamReader
    string line = sr.ReadLine();             // Read line from text file
    sr.Close();                              //close StreamReader after writing
}

Delete a text file:

if (File.Exists(path))      //Check if file exist or not
{
    File.Delete(path);      //if file exist then delete it           
}




Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved