Recipe 12.17. Reading and Writing Files as Strings


Problem

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.

Solution

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.

Discussion

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.

See Also

Recipe 12.18 discusses the processing of binary files.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net