VB.Net I/O Classes
The System.IO namespace has various class that are used for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file etc.The following table shows some commonly used non-abstract classes in the System.IO namespace:
| I/O Class | Description |
|---|---|
| BinaryReader | Reads primitive data from a binary stream. |
| BinaryWriter | Writes primitive data in binary format. |
| BufferedStream | A temporary storage for a stream of bytes. |
| Directory | Helps in manipulating a directory structure. |
| DirectoryInfo | Used for performing operations on directories. |
| DriveInfo | Provides information for the drives. |
| File | Helps in manipulating files. |
| FileInfo | Used for performing operations on files. |
| FileStream | Used to read from and write to any location in a file. |
| MemoryStream | Used for random access to streamed data stored in memory. |
| Path | Performs operations on path information. |
| StreamReader | Used for reading characters from a byte stream. |
| StreamWriter | Is used for writing characters to a stream. |
| StringReader | Is used for reading from a string buffer. |
| StringWriter | Is used for writing into a string buffer. |
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)For example, for creating a FileStream object F for reading a file named sample.txt:
Dim f1 As FileStream = New FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite)
| Parameter | Description |
|---|---|
| FileMode | The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
|
| FileAccess | FileAccess enumerators have members: Read, ReadWrite and Write. |
| FileShare | FileShare enumerators have the following members:
|
Example:
The following program demonstrates use of the FileStream class:Imports System.IO Module fileProg Sub Main() Dim f1 As FileStream = New FileStream("test.dat", _ FileMode.OpenOrCreate, FileAccess.ReadWrite) Dim i As Integer For i = 0 To 20 f1.WriteByte(CByte(i)) Next i f1.Position = 0 For i = 0 To 20 Console.Write("{0} ", f1.ReadByte()) Next i f1.Close() Console.ReadKey() End Sub End ModuleWhen the above code is compiled and executed, it produces following result:
No comments:
Post a Comment