Read and Write Text File in Asp.Net with C#
Read and Write Text File usin Asp.Net it's easy.
In C# when ever you want to do text file related operation than it’s very easy to do with lots of class and methods. All the Class file related to File Input Output operation are inside the System.IO name space. So, before writing anything in file just add name space to file using following line
using System.IO;
In this name space there are two classes TextWriter to write the text file and TextReader to read the file.
Writing something into text file
// Declare instance of writer class with following line
TextWriter tw = new StreamWriter("File.Text");
// In the above line we are declaring one text write and asign stream // writer to it.
// write three line of text to the file
tw.WriteLine(“My Name is Tarun \n”);
tw.WriteLine(“I am 25 year Old. \n”);
tw.WriteLine(“This file is wriiten at “ + DateTime.Now + “ \n”);
// close the stream
tw.Close();
Now your file is ready to use. But we want to read it progra mmatically
Most of the thing is same to read the file just we have to declare TextReader class rather than TextWriter
Here is the code to
Reading the whole file
// Declare one line variable with type string
string line = "";
// Now decalre TextReader class instance and open File.txt in memory stream.
TextReader tr = new StreamReader("File.Text");
// Now loop through all the line inside file and display one by one on the screen using Response.Write() Method.
while ((line = tr.ReadLine()) != null)
{
Response.Write(tr.ReadLine()+"<br>");
}
tr.Close();
In TextReader and Text Write class there are more methods to check file is there? When it is created? Who is the author, when last modify? Is it read only or not and many more just check one by one. You can manage total file handaling operation with this two class vry effectively.
Enjoy Reading and Writing Text File usin Asp.Net
0 comments:
Post a Comment