Reading and Writing Text Files with the .NET Framework, Part 2
By Scott Mitchell
In Part 1 we talked briefly about streams, and the role they play in reading and writing to files using the .NET Framework. We also saw how to read the contents from a text file. In this final part, we'll examine how to write to a text file.
Writing to a Text File
The
File
class provides two methods for writing to text files: CreateText()
and AppendText()
, both of which take the physical path to a file as its sole argument.
As their names suggest, CreateText()
is used for creating
new files while AppendText()
is useful for appending content to existing files. That is,
if the file that you pass into the CreateText()
function already exists, the file will be
overwritten. With AppendText()
if the file exists, the contents will be appended to the
end of this existing file's contents.
Both methods return a StreamWriter
object. The StreamWriter
has two
very useful methods for writing content to a file:
Write(stuff to write)
WriteLine(stuff to write)
Both methods have a number of overloaded versions, meaning that you can pass in a string, a character,
a number, or whatever, into either of these methods. The difference between the two, as their name
makes clear, is that WriteLine()
adds an end-of-line character after the input provided.
The following source code demonstrates how to append some output to an existing file. As with reading
the file, be certain to Close()
the stream when you are done writing the file.
|
The above code is relatively straightforward: it simply appends a string with the current date/time
to the file Output.txt
. After the writing stream is closed,
a stream for reading is opened, and the contents of the file are read and displayed in the Label
Web control.
Conclusion
In this article we examined how to read and write to text files through an ASP.NET Web page using the appropriate .NET Framework classes. We also discussed what streams are and their utility. When working with files through an ASP.NET Web page, be sure to keep security settings in mind. In order for code from an ASP.NET Web page to be able to muck with files, the ASPNET user account must have the appropriate permissions on the directory/files being tinkered with.
Happy Programming!