[ 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 =
TextBox2.Text = StreamReader1.ReadToEnd();
If the file does not exist you will get an error. You can check to see if the file exists using this code:
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 =
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.