Like this article? We recommend
Writing to a Text File
Text files are typically organized by lines, with a line end marked by a CR/LF. When writing to a text file, you have two options:
- Using the WriteLine() method to write some text as a line, with a CR/LF automatically added at the end
- Using Write() to write part of a line, with no CR/LF appended
These methods have the same syntax:
Write(item) WriteLine(item)
In both cases, item can be string data. It can also be any simple datatype such as Integer or Double, and can also be an object reference. For non-text data items, these rules are followed:
- For simple non-text data types, the data is converted to a string before being written to the file.
- For object references, the object’s ToString() method is called and the result written to the file.
Here’s an example that writes some text and the current date to a file.
sw = New StreamWriter("output.txt") sw.Write("This is the ") sw.WriteLine("first line of the file.") sw.WriteLine("=============") sw.Write("The date is: ") sw.WriteLine(DateTime.Now) sw.Close()
If you opened the output file in a text editor, it would look like this:
This is the first line of the file. ============= The date is: April 24, 2006