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 preceding section “Stream” for descriptions of those properties and methods.

FileStream adds two useful new properties to those it inherits from Stream. First, IsAsync returns True if the FileStream was opened asynchronously. Second, the Name property returns the filename passed into the object’s constructor.

The class also adds two new useful methods to those it inherits from Stream. 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 the following:

  • Filename or handle
  • 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)
  • Buffer size
  • File options (Asynchronous, DeleteOnClose, Encrypted, None, RandomAccess, SequentialScan, or WriteThrough)

Example program FileStreamWrite uses the following code to create a file. 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 & "	est.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

NOTE 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 http://unicode.org/faq/utf_bom.html and http://en.wikipedia.org/wiki/Unicode.

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 than the other classes. See the section “StringReader and StringWriter” describing these classes later in this chapter for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.45.253