The statements in Listing 11.11 demonstrate how to send various data types to a file. You can place the statements of this listing in a button’s Click event handler and then open the file with Notepad to see its contents. Everything is in text format, including the numeric values. Don’t forget to import the System.IO namespace to your project.
Listing 11.11: Writing Data to a Text File
Dim SW As StreamWriter
Dim FS As FileStreamFS = New FileStream("C:\TextData.txt", FileMode.Create)
SW = New StreamWriter(FS)
SW.WriteLine(9.009)
SW.WriteLine(1 / 3)
SW.Write("The current date is ")
SW.Write(Now())
SW.WriteLine()
SW.WriteLine(True)
SW.WriteLine(New Rectangle(1, 1, 100, 200))
SW.WriteLine(Color.YellowGreen)
SW.Close()
FS.Close()
Code language: PHP (php)
The contents of the TextData.txt file that was generated by the statements of Listing 15.11 are shown next:
9.009
0.333333333333333
The current date is 9/19/2005 9:06:46 AM
True
{X=1,Y=1,Width=100,Height=200}
Color [YellowGreen]
Code language: PHP (php)
Notice that the WriteLine method without an argument inserts a new line character in the file. The statement SW.Write(Now()) prints the current date but doesn’t switch to another line. The following statements demonstrate a more-complicated use of the Write method with formatting arguments:
Dim BDate As Date = #2/8/1960 1:04:00 PM#
SW.WriteLine("Your age in years is {0}, in months is {1}, " & _
"in days is {2}, and in hours is {3}.", _
DateDiff(DateInterval.year, BDate, Now), _
DateDiff(DateInterval.month, BDate, Now), _
DateDiff(DateInterval.day, BDate, Now), _
DateDiff(DateInterval.hour, BDate, Now))
Code language: PHP (php)
The SW variable must be declared with the statements at the beginning of Listing 15.11. The day I tested these statements, the following string was written to the file:
Your age in years is 47, in months is 569, in days is 17321, and in hours is 415726.
Of course, the data to be stored to a text file need not be hard-coded in your application. The code of Listing 11.12 stores the contents of a TextBox control to a text file. If you compare it to the single statement it takes to write the same data to a file with the FileSystem component, you’ll understand how much the My object can simplify file IO operations.
Listing 11.12: Storing the Contents of a TextBox Control to a Text File
Dim SW As StreamWriter
Dim FS As FileStream
FS = New FileStream("C:\TextData.txt", FileMode.Create)
SW = New StreamWriter(FS)
SW.Write(TextBox1.Text)
SW.Close ()
FS.Close ()
Code language: PHP (php)