The File and StreamWriter Classes
The StreamWriter class implements a TextWriter for writing characters to a stream in a particular encoding. StreamWriter is designed for character output in a particular encoding, whereas subclasses of Stream are designed for byte input and output.
StreamWriter defaults to UTF8Encoding unless specified otherwise . UTF-8 handles Unicode characters correctly and gives consistent results on localized versions of the operating system.
This section creates a sample application that enables users to write a message, and then saves the message to a disk file so that other users can read the message. The code that reads and displays the message file appears in the preceding section.
Creating a Text File
Before any data can be written to the disk, a file must be created. This is done in the example with the File.CreateText() method. The following code shows how to create a file named C:\Test\This\Out\Data.txt:
Dim strFilename as String strFilename = "C:\Test\This\Out\Data.txt" File.CreateText( strFilename )
Writing Data to a Text File
The File.CreateText() method returns a StreamWriter object. This is then used to write the data to the newly created disk file. The following code uses an already opened StreamReader to write a string to disk:
writer.Write( strTextData )
Figure 5.9 shows the sample application in use. Listing 5.10 shows the code that makes it work.
Figure 5.9. The File and StreamWriter classes make it easy to create and write text files.
Listing 5.10 Saving the Data That the User Entered into MessageText.txt
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim writer As StreamWriter Label1.Text = "" Try writer = _ File.CreateText(Request.MapPath("VisitorFiles\MessageText.txt")) writer.Write(TextBox1.Text) writer.Close() Label1.Text = "File was written successfully" TextBox1.Text = "" Catch ex As Exception Label1.Text = ex.Message End Try End Sub