![](/api/v2/epubs/0975240285/files/bg25d.png)
Visual Basic File: WriteFile.aspx (excerpt)
<script runat="server">
Sub WriteText(ByVal s As Object, ByVal e As EventArgs)
Using streamWriter As StreamWriter = File.CreateText( _
"C:\WebDocs\Learning\myText.txt")
streamWriter.WriteLine(myText.Text)
End Using
End Sub
</script>
C# File: WriteFile.aspx (excerpt)
<script runat="server">
void WriteText(Object s, EventArgs e)
{
using (StreamWriter streamWriter = File.CreateText(
@"C:\WebDocs\Learning\myText.txt"))
{
streamWriter.WriteLine(myText.Text);
}
}
</script>
Apart from the new Using construct, the code is pretty straightforward. First, we
create a StreamWriter variable called streamWriter. To obtain the variable’s
value, we call the CreateText method of the File class, passing in the location
of the text file, which returns a new StreamWriter. Don’t forget that C# needs
to escape backslashes when they’re used in strings, so the path to our file must
use \\ to separate folder names, or use the @ character in front of the string so
that backslashes are automatically ignored.
What about Using, then? Similarly to database connections, streams are some-
thing that we need to close when we’re done working with them, so they don’t
occupy resources unnecessarily. The Using construct is a common means of en-
suring that the stream is closed and disposed of after we work with it.
Disposing of Objects
Technically, when we work with Using, the object is disposed of, rather
than simply closed. The action is identical to explicitly calling its Dispose
method.
When the code enclosed by Using finishes executing, streamWriter’s
Dispose method is called automatically for you. This ensures that it doesn't
keep any resources locked, and that the object itself is removed from memory
immediately.
577
Writing Content to a Text File