Pages

Friday, July 20, 2012

Write to a text file using the FileStream StreamWriter class (ASP.NET)

Even though databases are probably the most popular method for storing data, there are still many applications that rely on basic text files for logging and error tracking. So, if you're writing to text files in .NET, then you need to get to know the StreamWriter class. The StreamWriter class is a member of the FileStream class, which provides all the functionality you need to read and write data to text files.

The following code creates a text file and writes two lines to it:

Dim fs As System.IO.FileStream
Dim sw As System.IO.StreamWriter
fs = New System.IO.FileStream("c:\txtfile.txt", _
System.IO.FileMode.Create)
sw = New System.IO.StreamWriter(fs)

sw.Write("Hello world! ")
sw.WriteLine("It's a joyous day.")

sw.Close()

Notice that we used two different methods to write to the file, Write and Writeline. Both methods send text to the file, but the FileStream class interprets the WriteLine string value as the end of the line.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.