CodeSnip: Read and Write Text Files with ASP.NET 2.0
page 1 of 1
Published: 19 Oct 2004
Unedited - Community Contributed
Abstract
Simple demonstration of reading and writing text files in ASP.NET 2.0 using the StreamReader and StreamWriter classes.
by Andrew Mooney
Feedback
Average Rating: 
Views (Total / Last 10 Days): 100978/ 66

[ Download Code ]

This is a simple demonstration of reading and writing text files in ASP.NET 2.0 using the StreamReader 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.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-09-22 12:51:55 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search