You have a rather large string that you need to be able to put into a file and get back later without too much hassle.
Sample code folder: Chapter 12\SimpleEditor
Use the My.Computer.FileSystem. WriteAllText() and related ReadAllText() methods to quickly get text data into and out of a file.
This recipe's sample code creates a simple Notepad-like text editor. Create a new Windows Forms application, and add two TextBox controls named FilePath and Editor and two Button controls named ActOpen and ActSave to the form. Set the Editor control's Multiline property to TRue and its ScrollBars property to Both. Add some informational labels, and arrange the controls to look like Figure 12-13.
Figure 12-13. Controls for the text editor sample
Add the following source code to the form's class template:
Private Sub ActOpen_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ActOpen.Click ' ----- Open an existing file and load its text. Try Editor.Text = My.Computer. FileSystem.ReadAllText(FilePath.Text) Catch ex As Exception MsgBox("Could not open the file due to the " & _ "following error:" & vbCrLf & vbCrLf & ex.Message) End Try End Sub Private Sub ActSave_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ActSave.Click ' ----- Save the edited data. If (My.Computer.FileSystem.FileExists(FilePath.Text) = _ True) Then If (MsgBox("File exists. Overwrite?", _ MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _ "Overwrite") <> MsgBoxResult.Yes) Then Exit Sub End If ' ----- Save the data. Try My.Computer.FileSystem.WriteAllText(FilePath.Text, _ Editor.Text, False) Catch ex As Exception MsgBox("Could not save the file due to the " & _ "following error:" & vbCrLf & vbCrLf & ex.Message) End Try End Sub
To use the program, type in a file path, and click the Open button. Make changes in the Editor field, and then click the Save button to store those changes in the file.
The My.Computer. FileSystem.ReadAllBytes() and WriteAllBytes() methods provide parallel features for byte arrays.
Recipe 12.18 discusses the processing of binary files.