5.4. Read and Write Files
If you need to work with text files or raw binary data, VB 2005 provides a new solution that bypasses the lower-level classes of System.IO for small files. Now you can read and write text in a single atomic operation using the My.Computer.FileSystem object. Best of all, you no longer need to create streams, track your position, or clean up afterward.
Note: At last, a way to read and write files without the complexities of streams and stream readers.
5.4.1. How do I do that?
The My.Computer.FileIO object provides the absolute quickest way to read or write the contents of a file. Its secret lies in a few self-contained methods. These include:
Example 5-4 creates a simple text file and then reads it back into memory.
Example 5-4. Write a file in one step and read a file in one step
Imports System.IO Module FileReadAndWrite Public Sub Main( ) Dim Text As String = "This is line 1" & _ vbNewLine & "This is line 2" & _ vbNewLine & "This is line 3" & _ vbNewLine & "This is line 4" ' Write the file. My.Computer.FileSystem.WriteAllText("c:\test.txt", Text, False) ' Read the file. Console.WriteLine(My.Computer.FileSystem.ReadAllText("c:\test.txt")) End Sub End Module
5.4.2. What about...
...the limitations of this approach? The methods that you'll find in the My.Computer.FileSystem object are unmatched for sheer convenience, but they aren't always appropriate. Here are some reasons you might be better off using the lower-level classes of the System.IO namespace:
The core .NET classes for reading and writing files are found in the System.IO namespace and haven't changed in .NET 2.0. The most useful of these are FileStream (allows you to open a file directly for reading or writing), StreamReader and StreamWriter (used for reading and writing text, one line at a time), and BinaryReader and BinaryWriter (used for converting basic .NET data types to binary data and back). Look these classes up in the MSN Help for the traditional file-access techniques. Also, in the next lab, you'll see a more advanced example that uses FileStream to encrypt data in a file.