346 Part II Programming Fundamentals
To Do This
Write a text file
by using the My
namespace
Use the My.Computer.FileSystem object and the WriteAllText method. For
example (assuming that you are also using a save file dialog object named
sfd and a text box object named txtNote):
sfd.Filter = "Text files (*.txt)|*.txt"
If sfd.ShowDialog() = DialogResult.OK Then
My.Computer.FileSystem.WriteAllText( _
sfd.FileName, txtNote.Text, False)
End If
Write a text file
by using the
StreamWriter class
Add the statement Imports System.IO to your form’s declaration section,
and then use StreamWriter. Use the Write method to write the text. When
finished, call the Close method. For example, to write the contents of a text
box object named TextBox1 to a file:
Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter( _
"c:\vb10sbs\chap13\output.txt")
StreamToWrite.Write(TextBox1.Text)
StreamToWrite.Close()
Write a text file line
by line
Use StreamWriter and the WriteLine method. Use the OpenTextFileWriter
method in the My namespace to open a StreamWriter:
Dim LineOfText As String = ""
Dim StreamToWrite As StreamWriter
StreamToWrite = My.Computer.FileSystem.OpenTextFileWriter( _
"C:\vb10sbs\chap13\output.txt", False)
LineOfText = InputBox("Enter line")
Do Until LineOfText = ""
StreamToWrite.WriteLine(LineOfText)
LineOfText = InputBox("Enter line")
Loop
StreamToWrite.Close()
Process strings Use the String class. Some of the members of String include:
n Compare
n CompareTo
n Contains
n EndsWith
n IndexOf
n Insert
n Length
Convert a string
with separators to
an array
Use the Split method on the String class. For example:
Dim AllText As String = "a*b*c*1*2*3"
Dim strArray() As String
strArray = AllText.Split("*")
'strArray = {"a", "b", "c", "1", "2", "3"}
n Remove
n Replace
n StartsWith
n Substring
n ToLower
n ToUpper
n Trim