Pages

Subscribe:

Ads 468x60px

Thursday, March 15, 2012

how to Read and write text file in asp.net using c#

In this web programming tutorial we will learn that how we can read a text file in asp.net using c# and how we can write some text or data on a text file in asp.net using c#.

Reading and writing (File manipulation) is a very easy task in asp.net, in this tutorial we will learn that how simply write data on a text file and read data from a text file.
suppose we have a Text file named "abc.txt" in the root folder of our web application.

if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/abc.txt")))
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
sw.Write("Hello world");
sw.Dispose();
}
if you want to Append data in the Text file then you have to set append parameter true in StramWriter object constructor.
Eg:-
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"),true);

we need to create a streamwriter object to write lines of data into a text file, follow this MSDN article to understand more about StreamWriter class.

Read Data From Text File:
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.txt")))
{
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
string strdata = sr.ReadToEnd();
sr.Dispose();
}

No comments:

Post a Comment