0
Posted on 10:12 PM by prajeesh and filed under ,
File manipulation is a very easy task in asp.net, i this article i will show you a simple example that writes and and read data from a text file.
suppose we have a Text file named "TestFile.txt" in the root folder of our web application.
Writing Data to a text file :
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.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.

Reading Data from a 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();

}
we have to create a StreamReader object to read data from a text file, follow this MSDN article to know more about StreamReader class.
Data will be available in strdata variable.

Shout it kick it on DotNetKicks.com
0
Responses to ... Reading and writing text files using asp dot net