Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
Chapter 13 Quick Reference
To | Do this |
Open a text file | Use the FileOpen function. For example:
FileOpen(1, OpenFileDialog1.FileName, _ OpenMode.Input) |
Get a line of input from a text file | Use the LineInput function. For example:
Dim LineOfText As String LineOfText = LineInput(1) |
Check for the end of a file | Use the EOF function. For example:
Dim LineOfText, AllText As String Do Until EOF(1) LineOfText = LineInput(1) AllText = AllText & LineOfText & _ vbCrLf Loop |
Close an open file | Use the FileClose function. For example:
FileClose(1) |
Display a text file by using LineInput | Use the LineInput function to copy text from an open file to a string variable, and then assign the string variable to a text box object. For example:
Dim AllText, LineOfText As String Do Until EOF(1) 'read lines from file LineOfText = LineInput(1) AllText = AllText & LineOfText & _ vbCrLf Loop txtNote.Text = AllText 'display file |
Display a text file by using the StreamReader class | Add the statement “Imports System.IO” to your form's declaration section, and then use StreamReader. For example, to display the file in a text box object named TextBox1:
Dim StreamToDisplay As StreamReader StreamToDisplay = _ New StreamReader("c:\vb05sbs\chap13\text browser\badbills.txt") TextBox1.Text = StreamToDisplay.ReadToEnd StreamToDisplay.Close() TextBox1.Select(0, 0) |
Display a text file by using the My object | Use the My.Computer.FileSystem object and the ReadAllText method. For example, assuming that you are also using an open file dialog object named ofd and a text box object named txtNote:
Dim AllText As String = "" ofd.Filter = "Text files (*.TXT)|*.TXT" ofd.ShowDialog() If ofd.FileName <> "" Then AllText = _ My.Computer.FileSystem.ReadAllText(ofd.FileName) txtNote.Text = AllText 'display file End If |
Display an Open dialog box | Add an OpenFileDialog control to your form, and then use the ShowDialog method of the open file dialog object. For example:
OpenFileDialog1.ShowDialog() |
Create a new text file | Use the FileOpen function. For example:
FileOpen(1, SaveFileDialog1.FileName, _ OpenMode.Output) |
Display a Save As dialog box | Add a SaveFileDialog control to your form, and then use the ShowDialog method of the save file dialog object. For example:
SaveFileDialog1.ShowDialog() |
Save text to a file | Use the Print or PrintLine function. For example:
PrintLine(1, txtNote.Text) |
Convert text characters to ASCII codes | Use the Asc function. For example:
Dim Code As Short Code = Asc("A") 'Code equals 65 |
Convert ASCII codes to text characters | Use the Chr function. For example:
Dim Letter As Char Letter = Chr(65) 'Letter equals "A" |
Extract characters from the middle of a string | Use the Substring method or the Mid function. For example:
Dim Cols, Middle As String Cols = "First Second Third" Middle = Cols.SubString(6, 6) 'Middle = "Second" |