Search This Blog

Saturday 17 September 2011

How can Read and Write Text Files with ASP.NET?


In most of the cases, asp.net developer needs to work with read and write text files from the local folder. By using this function, developer can write and save any errors occurred in the application to a txt files and can refer later. Also having so many chances for this function in various domain.
This is a simple explanation of reading and writing text files in ASP.NET 2.0 using theStreamReader and StreamWriter classes.
To read a text file using the System.IO.StreamReader class into a TextBox control use the following code:
System.IO.StreamReader StreamReader1 =
new System.IO.StreamReader(Server.MapPath(“test.txt”));
TextBox2.Text = StreamReader1.ReadToEnd();
StreamReader1.Close();
If the file does not exist you will get an error. You can check to see if the file exists using this code:
if (System.IO.File.Exists(Server.MapPath(“test.txt”)))
To write the contents of a TextBox control to a text file using the System.IO.StreamWriter class use the following code:
System.IO.StreamWriter StreamWriter1 =
new System.IO.StreamWriter(Server.MapPath(“test.txt”));
StreamWriter1.WriteLine(TextBox1.Text);
StreamWriter1.Close();
In the above example the StreamWriter class will create the text file if it does not exist and over write the file if it does exist. Line breaks in a TextBox control that uses multiline mode will show up in the text file.
Inserting “\r\n” will create a line break in the text file. Adding line breaks from code can be done using this code:
StreamWriter1.WriteLine(“Some text on line1.\r\nSome text on line2.”);
The dowload contains a web page containing two TextBox controls. Edit the TextBox on top and click the save button. A text file will be created using the text in the top TextBox and saved in the same virtual directory as the web page. The new text file is then loaded into the bottom TextBox to show that changes were saved.
This simple example has demonstrated a couple of the more frequent uses for the StreamReader and StreamWriter classes. They can be used with all kinds of text files including XML, web pages, classes (.cs or .vb), and many more.

No comments:

Post a Comment