FileStream


The FileStream class provides a stream representation of a file.

The FileStream class’s parent class Stream defines most of its properties and methods. See the section “Stream” earlier in this chapter for descriptions of those properties and methods.

FileStream adds two useful new properties. First, IsAsync returns True if the FileStream was opened asynchronously. Second, the Name property returns the file name passed into the object’s constructor.

The class also adds two new useful methods. The Lock method locks the file, so other processes can read it but not modify it. Unlock removes a previous lock.

Overloaded versions of the FileStream class’s constructor let you specify a file name or handle, the file mode (Append, Create, CreateNew, Open, OpenOrCreate, or Truncate), access mode (Read, Write, or ReadWrite), file sharing (Inheritable, which allows child processes to inherit the file handle; None, Read; Write; or ReadWrite), a buffer size, and file options (Asynchronous, DeleteOnClose, Encrypted, None, RandomAccess, SequentialScane, or WriteThrough).

The following code shows a small example that uses a FileStream. It creates a file and uses a Universal Transformation Format (UTF) UTF8Encoding object to convert a string into an array of bytes. It writes the bytes into the file and then closes the FileStream.

  Dim file_name As String = Application.StartupPath & "\test.txt" Using file_stream As New FileStream(file_name, FileMode.Create)     Dim bytes As Byte() = New UTF8Encoding().GetBytes("Hello world!")     file_stream.Write(bytes, 0, bytes.Length)     file_stream.Close() End Using 

Tip 

The 8-bit UTF encoding is the most popular type on the Web, although there are other encoding formats such as UTF-7 and UTF-16. For additional information, see zsigri.tripod.com/fontboard/ cjk/unicode.html.

As this example demonstrates, the FileStream class provides only low-level methods for reading and writing files. These methods let you read and write bytes, but not integers, strings, or the other types of data that you are more likely to want to use.

The BinaryReader and BinaryWriter classes let you read and write binary data more easily than the FileStream class does. The StringReader and StringWriter classes let you read and write string data more easily. See the section “StringReader and StringWriter” describing these classes later in this chapter for more information.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

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